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?
Even though your
frm variable isn’t
Nothing, the form is unloaded. Add a little check before and after the
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”
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