0
votes

I have the following code which is supposed to load a userform, and then execute some code if the cancel button on the form isn't clicked.

Sub test()
    Dim frm As Userform1
    
    Set frm = New Userform1
    
    frm.Show
    
    If Not frm Is Nothing Then
        Debug.Print "test"
    End If
End Sub

The code for the cancel button is simply

Private Sub cmdCancel_Click()
    Unload Me
End Sub

I was expecting the frm object in the first code snippet to be set back to nothing when the userform was unloaded, but apparently that's not the case as "test" is printed to the immediate window whether I click cancel or not. Is there any simple way to check if the frm-object points to a loaded userform or not?

1
IMO forms shouldn't unload themselves, they should simply hide and the code that called them should take care of the rest.Rory
How should frm know that the the userform destroyed itself. You will get an automation error when you try to access a property of the form. You need to take care of removing the userform yourself with Unload frm. May this article gives more insight.Storax
That looks quite interesting @EvR, I'll have a closer look at it and probably refactor my code. If you feel up to summarizing the parts of it pertinent to my question as an answer, I'll mark it as a solution.eirikdaude

1 Answers

0
votes

I'd suggest to create for debugging purposes the following class clsExample

Option Explicit

Dim mObject As Variant

Property Get obj() As Object
    Set obj = mObject
End Property

Function Cancel()
    Set mObject = Nothing
End Function

Property Get version()
    version = mObject.version
End Property

Private Sub Class_Initialize()
    Set mObject = Application
End Sub

And then use the debugger to go stepwise through the following code

 Sub TestClass()

    Dim my As New ClsExample
    Set my = New ClsExample
    
    Debug.Print my.version
    my.Cancel
       

    If Not my Is Nothing Then
        Debug.Print "Test"
    End If
    
    Debug.Print my.version

End Sub