How to create a Userform
Article contributed by Doug Robbins
This example will step you through the process of creating a template that contains an autonew macro which, when you create a new document from the template, will cause a Userform to be displayed, into which you can enter some information that you want to appear in the document.
For example, when creating a letter or a fax; when you click on the OK button on the Userform, the information that has been entered into it will be inserted into bookmarks located in the document at the places that you want the information to appear.
The example shows how you would deal with two pieces of information that you want to put into the document. At pertinent places in the following, comments have been added indicating where you would modify the code to deal with more pieces of information.
Step |
Comments |
||
|
See: Creating a Template – The Basics (Part I) and Creating a Template (Part II) |
||
|
Add additional bookmarks for each piece of data) Use more descriptive names for the bookmarks if you like as it does make it easier to remember which is which and what goes where |
||
|
Alternatively, you can hold down the Alt key and press F11 |
||
|
A UserForm will appear in the right hand pane and the Controls toolbox will appear in the left hand pane. If there are no other Userforms in the Template, it will by default be UserForm1. |
||
|
By default, the TextBoxes will be numbered TextBox1, TextBox2 ...TextBoxn. You can change the names of the TextBoxes in the Properties window in the left hand pane. If you name them the same as the Bookmarks that you inserted into the template in Step 1, it makes it easier |
||
|
|||
|
|||
|
By default, this will be named CommandButton1 |
||
|
|||
|
Repeat the lines beginning with Similarly, you can insert the same information into a second bookmark by inserting a line referring to the range of that bookmark |
||
|
|||
|
|||
|
|||
|
When you create a new document from the template, the autonew macro opens the user form for the user to input data, then when the command button is clicked, the code associated with that button inserts each piece of information into the respective bookmark.
This has been restricted to just enough to get you started. There's lots more that you can do with UserForms. If you get stuck, post a question to the microsoft.public.word.vba.userforms newsgroup and someone will spring to your rescue..