Search code examples
vbams-worduserform

How can I show a userform and wait for code to run, while still being able to access other documents?


In Word VBA, I want to show a userform and input information in textboxes and checkboxes.
However, I would like to be able to access and scroll in other Word documents.

I want a userform to pop up, insert text and click checkboxes, be able to scroll in other documents, and then press a command button to hide the userform and execute the rest of the code.

I set the userform feature ShowModal to False. This helped me access other documents and be able to scroll in them.
However, my code will keep executing, so I cannot use the information in the textboxes and checkboxes from the userform, or even have a user insert information into the textboxes.

A simple script to show this concept.

Sub testing()
UserForm1.Show
MsgBox ("Hello, " + UserForm1.TextBox1.Value)
Unload UserForm1
End Sub

The userform is shown below.
Image of userform

I want to open the userform, insert a name while being able to click around in another Word document, then click the OK button. If I change it to Userform1.Show vbModeless, the message box will output "Hello, " and then close the userform afterward.


Solution

  • You need to break up testing into two subs - the first just shows the form non-modally and then exits, and the second is called from the userform when your user is ready to proceed. Code in the userform passes any required parameters (or a reference to itself so the called code can access any required info from the form) to the second sub.

    For example:

    In Module1:

    Sub ShowForm()
        Dim frm As New UserForm1
        frm.Show False
    End Sub
    
    Sub ProcessForm(frm As UserForm1)
        MsgBox frm.TextBox1.Text
        Unload frm
    End Sub
    

    In the form:

    Private Sub CommandButton1_Click()
        Application.Run "Module1.ProcessForm", Me
    End Sub