7

I have the following code opening a form and then doing some stuff.

Sub lag_ny_a3()
    Dim frm As ufNyA3

    Set frm = New ufNyA3
    frm.Show

    If Not frm Is Nothing Then
        MsgBox("Doing stuff")
        Unload frm
    End If
End Sub

Then I have the following code in my form

Private Sub cmdAvbryt_Click()
    Unload Me
End Sub

However, even if the cmdAvbryt-button is clicked in the form, the first code-snippet enters the if-statement, as if the form is not unloaded. Why is this, and how can I prevent the code in the if-statement to be executed if the cmdAvbryt-button is pushed?

eirikdaude
  • 3,106
  • 6
  • 25
  • 50
  • 3
    The `frm` is not `Nothing` because it was `Set`ed before. And `Unload` the form does not unset the variable. `Set frm = Nothing` would doing this. – Axel Richter May 28 '18 at 07:50

2 Answers2

4

Even though your frm variable isn't Nothing, the form is unloaded. Add a little check before and after the frm.Show:

Debug.Print VBA.UserForms.Count
frm.Show
Debug.Print VBA.UserForms.Count

and you'll see that it is not in the list of loaded forms. If you set the object variable to Nothing it will not do the "Doing stuff"

Sam
  • 5,424
  • 1
  • 18
  • 33
3

Actually, frm declared as ufNyA3 will not become Nothing after the userform unloading. Try to use the following IsUserFormLoaded() function to check if the userform is loaded:

Sub lag_ny_a3()

    Dim frm As ufNyA3

    Set frm = New ufNyA3
    frm.Show

    If IsUserFormLoaded("ufNyA3") Then
        MsgBox ("Doing stuff")
        Unload frm
    Else
        MsgBox ("Unloaded")
    End If

End Sub

Function IsUserFormLoaded(UserFormName As String) As Boolean

    Dim frm

    For Each frm In UserForms
        IsUserFormLoaded = LCase(frm.Name) = LCase(UserFormName)
        If IsUserFormLoaded Then Exit For
    Next

End Function
omegastripes
  • 12,351
  • 4
  • 45
  • 96