我正在编写一个vba代码,我将设置一些公共var用于许多潜艇 在用户表单代码中声明的变量如此
public xxxx as string
sub vars()
xxxx = "test"
end sub
Private Sub CommandButton1_Click()
' test button
MsgBox ("pub var is " & xxxx)
End Sub
当我点击测试按钮时,msg框为空白,看起来好像无法看到pub var aney想法问题在哪里 (即使我将公共xxxx设置为模块或本工作簿的代码中的srtring,我得到相同的结果) 感谢
答案 0 :(得分:2)
我看起来很明显,所以我可能误解了这个问题。
您未在任何地方调用vars()
,因此字符串xxxx
初始化为其默认值(空白)。如果您更改代码以按如下方式调用vars()
:
Private Sub CommandButton1_Click()
' call vars() to set the string value
vars
' test button
MsgBox ("pub var is " & xxxx)
End Sub
然后它将按预期工作。
在我的测试中,即使我首先单独调用vars()
,然后在发布时调用button_click,也会正确设置xxxx
的值。显然,这个值在关闭Excel并重新启动它后仍然无法生存。在这种情况下,您需要在某处向外部保存其值,并在重新启动Excel时重新加载它。