Search code examples
excelvbauserform

How to have VBA code wait until vbModeless userform is closed


I'd like to use a modeless userform so the user can navigate the Excel sheet before answering the question on the userform. I need to pause or loop the code until the userform is closed (hidden or unloaded).

Similar issue: How can I wait for a specific code to run while when form is closed and is set to vbModeless?
The solution here does not work for my application. My userform is opened in the middle of a long subroutine which needs to finish executing after the userform is closed.

Dim popupActive as Boolean

popupActive = True
StartingSINT_Popup.Show vbModeless 'Open userform

'have VBA code wait until userform is closed
wait until popupActive = False 'set to false with OK button on userform

'continue code with info input inside StartingSINT_Popup userform

Solution

  • I didn't author the following function, but I have used it for a long time and it works.

    Private Function IsLoaded(ByVal formName As String) As Boolean
        Dim frm As Object
        For Each frm In VBA.UserForms
            If frm.Name = formName Then
                IsLoaded = True
                Exit Function
            End If
        Next frm
        IsLoaded = False
    End Function
    

    You will need to hardcode the string name, and not use the .Name property of the form because the form may not be loaded yet and not contain this property.

    Here is a small snippet of how you can use this function:

    Do While IsLoaded("StartingSINT_Popup")
        Debug.Print Time; " StartingSINT_Popup Is Loaded!"
    Loop