为什么关闭用户窗体时 VBA 全局变量会丢失值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25004689/
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
Why VBA global variables loses values when closing UserForm?
提问by Ga?per Sladi?
I have a macro code behind Worksheet. When button is clicked on the sheet, new user form is initialised and showed to user. If user closes the windows with red X, or form is closed with "hide" function/method, all global variables that are behind Worksheet loses their values. Is it possible to preserve this values?
我在工作表后面有一个宏代码。当点击表单上的按钮时,新的用户表单被初始化并显示给用户。如果用户使用红色 X 关闭窗口,或者使用“隐藏”函数/方法关闭表单,则 Worksheet 后面的所有全局变量都将丢失其值。是否可以保留这些值?
Worksheet code behind:
后面的工作表代码:
Private MeasurementCollection As Collection
Dim CurrentMeasurement As measurement
Dim NewMeasurement As measurement
Private Sub Worksheet_Activate()
Initialize
End Sub
Public Sub Initialize()
Set NewMeasurement = New measurement
Dim DropDownDataQueries As Collection
Set DropDownDataQueries = DBQueries.GetAllUpdateQueries
For i = 1 To DropDownDataQueries.Count
Dim Values As Collection
Set Values = DataBase.GetData(DropDownDataQueries(i))
With Me.OLEObjects("Combo" & i).Object
For Each value In Values
.AddItem value
Next value
End With
Next i
End Sub
Private Sub UpdateDB_Click()
UpdateGeneralData
If (CurrentMeasurement Is Nothing) Then
MsgBox ("Message text")
Else
Dim form As UpdateComentForm
Set form = New UpdateComentForm
form.Show
End If
End Sub
Private Sub Combo1_Change()
If Application.EnableEvents = True Then
If (Combo1.value <> "") Then
NewMeasurement.DN = Combo1.value
Else
NewMeasurement.DN = 0
End If
End If
End Sub
UserForm code
用户表单代码
Private Sub UpdateDBData_Click()
If (Komentar.value <> "") Then
Me.Hide
Else
MsgBox ("Prosimo napi?ite vzrok za spremembe podatkov v belo polje!")
End If
End Sub
Private Sub UserForm_Terminate()
Me.Hide
End Sub
回答by GSerg
Experiments show that the module-level variables are cleared upon exiting a procedure that involves calling = New Form
, provided that the form designer window is opened somewhere in the IDE.
实验表明= New Form
,如果表单设计器窗口在 IDE 中的某处打开,则在退出涉及调用的过程时会清除模块级变量。
Close all user forms designer windows you might have open in the VBA IDE and try again.
关闭您可能在 VBA IDE 中打开的所有用户窗体设计器窗口,然后重试。
回答by stenci
NewMeasurement as been declared but never assigned.
NewMeasurement 已声明但从未分配。
You could do something like Dim NewMeasurement As New measurement
to create an instance of the object.
您可以执行类似Dim NewMeasurement As New measurement
创建对象实例的操作。