Question

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?

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
Was it helpful?

Solution

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.

Close all user forms designer windows you might have open in the VBA IDE and try again.

OTHER TIPS

NewMeasurement as been declared but never assigned.

You could do something like Dim NewMeasurement As New measurement to create an instance of the object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top