Excel - VBA:将变量从Sub传递给Userform

Pha*_*anx 8 variables excel vba userform

我已经阅读并应用了类似主题的解决方案,但在我的案例中似乎没有任何效果.

所以,我想将一个变量从我的Module1的一个子传递给一个userform.这是一个名为"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
Run Code Online (Sandbox Code Playgroud)

然后在我的userform代码中:

Private Sub userformBtn1_Click()

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

End Sub
Run Code Online (Sandbox Code Playgroud)

当我运行我的程序时:

1 /我有来自my sub的MsgBox中显示的provinceSugg的内容(因此有一个provinceSugg,它不是一个空变量).
2 /从userform调用的MsgBox为空(因此传递值失败)并且我的程序在运行"sMain.Range("J6")时崩溃.值= provinceSugg",类似于"Error 424 Object Required"(所以变量无法传递给userform).

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

在此先感谢您的帮助 !

小智 9

您可以在Userform中创建可由模块设置的公共变量.

这些变量只能在加载时在Userform中访问.

在Userform中,声明两个对象的公共变量.

Public sMain As Worksheet
Public provinceSugg as string

Private Sub userformBtn1_Click()

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

End Sub
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

  • 您是否必须重置或清除这些公共变量以防止内存泄漏,或者在窗体关闭时这些公共变量是否会消失? (3认同)