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

Time:01-06

In Word VBA, I want to be able 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. So, 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 have tried to use the userform feature ShowModal and set it 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 have made 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.

I have not found another question that solved this exact problem, so hopefully you can guide me to solve this issue.

CodePudding user response:

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
  •  Tags:  
  • Related