12

我已经阅读并应用了我在类似主题上找到的解决方案,但在我的情况下似乎没有任何效果。

所以,我想将一个变量从我的 Module1 的一个子传递到用户窗体。这是一个名为“provinceSugg”的字符串。

这是我的代码的相关部分:

Public provinceSugg As String

Sub probaCity()
[...]
If province = "" And city <> "" Then
provinceSugg = sCurrent.Cells(p, db_column).Offset(0, 1).Value
UserForm2.Label1 = "Do you mean " & city & " in " & provinceSugg & " ?"
UserForm2.Label1.TextAlign = fmTextAlignCenter
UserForm2.Show
Else
End If

End Sub

然后在我的用户表单代码中:

Private Sub userformBtn1_Click()

MsgBox provinceSugg
sMain.Range("J6").Value = provinceSugg

End Sub

当我运行我的程序时:

1/我的 sub 调用的 MsgBox 中显示了 ProvinceSugg 的内容(所以有一个 ProvinceSugg,它不是一个空变量)。
2/从用户窗体调用的 MsgBox 是空的(因此传递值失败)并且我的程序在运行“sMain.Range("J6").Value = ProvinceSugg”时崩溃,类似于“需要错误 424 对象”(因此变量未能传递给用户表单)。

我尝试了我在论坛和这里找到的所有东西(表明 ProvinceSugg 是一个公共变量但仍然崩溃的不同方式......)。

在此先感谢您的帮助 !

4

2 回答 2

12

您将能够在可由模块设置的用户表单中创建公共变量。

这些变量只能在加载时在用户窗体中访问。

在用户窗体中,为两个对象声明公共变量。

Public sMain As Worksheet
Public provinceSugg as string

Private Sub userformBtn1_Click()

MsgBox provinceSugg
sMain.Range("J6").Value = provinceSugg

End Sub

在模块中,您可以评估这两个变量。

Sub probaCity()
[...]
If province = "" And city <> "" Then

    provinceSugg = sCurrent.Cells(p, db_column).Offset(0, 1).Value

    With UserForm2
        .provinceSugg = provinceSugg 
        Set .sMain = sMain 
        .Label1 = "Do you mean " & city & " in " & provinceSugg & " ?"
        .Label1.TextAlign = fmTextAlignCenter
        .Show
    End With

End If

End Sub
于 2013-12-03T14:37:05.603 回答
2
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim selectColumn
selectColumn= Split(Target.Address(1, 0), "$")(0)

Call UserFormStart(selectColumn)
End Sub

Inside Main Module

Public columnSelection As String
...
Public Sub UserFormStart(ByVal columnRef As String)
    'MsgBox "Debug columnRef=" & columnRef
    columnSelection = columnRef
    UserForm1.Show
End Sub

Inside UserForm

Private Sub UserForm_Initialize()

'MsgBox "Debug UserForm_Initialize =" & columnSelection
...

End Sub

Worksheet_SelectionChange calls a sub on the module where columnSelection is declared as public and visable from the UserForm. I used three different variables for the Column Reference to show that there is where the UserForm has access to the Module. The above all works and took ages to find and work out hence the submission. Happy hunting folks

于 2017-05-09T17:51:16.387 回答