How to have VBA code wait until vbModeless userform is closed

后端 未结 3 973
南方客
南方客 2021-02-11 02:48

I\'d like to use a formless 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

3条回答
  •  梦谈多话
    2021-02-11 03:04

    Here is an alternative...

    1. In the original [public] module (the one that calls userform 1), declare a public Boolean variable.

    Public done As Boolean

    2. In userform 1,

    a. Assign a default value to the Boolean variable

    b. Call Userform 2

    c. Have a do while loop that...

    • checks for that default value
    • includes the DoEvents method (allows userform 2 to push through despite loop)

    Code

        Private Sub event_click()
    
        done = False
    
        Dim userform2 As New userform
        userform2.Show Modeless
    
        'This will loop through until userform2 changes done variable to "True"
        Do While done = False
        DoEvents
        Loop
    
        'Code after done with userform2
        dataSource.Refresh
    
        End Sub
    

    3. In userform 2, change value of Boolean to break loop

    Code

        Private Sub submit_Click()
    
        'Userform submit code
        Dim name As String        
        name = TextBox.Value
        sql = "INSERT INTO table (field) VALUES ('" & name & "')"        
        Call query(sql)
    
        'IMPORTANT: change Boolean variable to break loop before exiting userform
        done = True
    
        Unload Me
    
        End Sub
    

提交回复
热议问题