关闭UserForm时为什么VBA全局变量会丢失值?

时间:2014-07-28 21:30:30

标签: vba variables excel-vba userform excel

我在工作表后面有一个宏代码。在工作表上单击按钮时,将初始化新用户表单并显示给用户。如果用户使用红色X关闭窗口,或者使用“隐藏”功能/方法关闭窗体,则Worksheet后面的所有全局变量都会丢失其值。是否可以保留这些值?

背后的工作表代码:

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代码

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

2 个答案:

答案 0 :(得分:6)

实验表明,在退出涉及调用= New Form的过程时,模块级变量会被清除,前提是在IDE中的某个位置打开了表单设计器窗口。

关闭可能已在VBA IDE中打开的所有用户窗体设计器窗口,然后重试。

答案 1 :(得分:-1)

已宣布但未分配的NewMeasurement。

您可以执行Dim NewMeasurement As New measurement之类的操作来创建对象的实例。