VBA 全局变量值在其他子程序中消失
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16446521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA global variable value disappear in other sub
提问by Arielsp
I have a global variable called flag set up. I can access flag from every module in my code, but when I assign it the value 1 in Sub Command97_Click(), for some reason flag does not keep the value to Sub Form_BeforeUpdate(Cancel As Integer). When I print the flag in Sub Form_BeforeUpdate it is not equal to 1 anymore. I know that this is silly, but I am new to vba...
我设置了一个名为 flag 的全局变量。我可以从我的代码中的每个模块访问标志,但是当我在 Sub Command97_Click() 中为它分配值 1 时,由于某种原因,标志不会将值保留为 Sub Form_BeforeUpdate(Cancel As Integer)。当我在 Sub Form_BeforeUpdate 中打印标志时,它不再等于 1。我知道这很愚蠢,但我是 vba 新手...
Bear in mind my code does more than this, but I am only keeping the basic for my question.
请记住,我的代码不仅仅如此,但我只保留了我的问题的基本知识。
Thanks in advance!
提前致谢!
Public flag As Integer
Private Sub Command97_Click()
flag = 1
End Sub
Private Sub Form_BeforeUpdate(Cancel As Integer)
If flag = 1 Then
DoCmd.RunCommand acCmdUndo
MsgBox "Flag = " & flag, vbInformation
Exit Sub
End If
End Sub
回答by Tom Collins
I suspect you have a variable scope issue. It depends on where your flag variable is defined, and are there others with the same name elsewhere.
If you say Public flag as Integer
at the top of a form module, then it's not really global.
我怀疑你有一个可变范围的问题。这取决于您的标志变量的定义位置,以及其他地方是否有其他同名变量。
如果你说Public flag as Integer
在表单模块的顶部,那么它就不是真正的全球性的。
回答by OlimilOops
Search for "public flag" and "global flag" in all your modules, maybe you have this variable name twice.
It's possible to distinguish between two equally named variables in different standard-modules if you set the module-name before it:
在所有模块中搜索“public flag”和“global flag”,也许你有两次这个变量名。
如果在它之前设置模块名称,则可以区分不同标准模块中的两个同名变量:
Module1.flag = 1
Module2.flag = 1
and in form-modules use
并在表单模块中使用
Me.flag = 1
to make sure which flag you use at the moment.
以确保您目前使用哪个标志。