Lafayette07 wrote:
> I'm pretty new to VBA, so I'm running into some issues using Option
> Buttons on a UserForm. The UserForm I've made has a number of
> textboxes which fill in bookmarks on a lab report (that part works
> fine), and 3 option buttons. The option buttons correspond to 3
> people's names. What I would like to do is have the user select
> which person is the contact person, using the option buttons, and
> then have the name and contact information (address, phone, fax,
> email address) appear on the first page of a report. I don't really
> know how to set up a macro (I'm assuming that's what I need) to put
> the information where I want it. Can anyone help?
>
>
> Thanks in advance.
>
>
> Sara
Using option buttons on a userform is a lot like using the textboxes, except
that the text to put into the document has to be stored within the code of
the userform or imported from somewhere else.
For example, let's assume your document has two bookmarks named contactName
and contactPhone that are to be filled in. The userform has three option
buttons named optSara, optNancy, and optBill. You could write the code in
the userform this way (rather than repeat the code for inserting text at a
bookmark for each of the three options, I've made a subroutine of it):
Private Sub cmdOK_Click()
If optSara.Value Then
FillBookmark "contactName", "Sara"
FillBookmark "contactPhone", "4037"
ElseIf optNancy.Value Then
FillBookmark "contactName", "Nancy"
FillBookmark "contactPhone", "2885"
ElseIf optBill.Value Then
FillBookmark "contactName", "Bill"
FillBookmark "contactPhone", "6384"
End If
Unload Me
End Sub
Private Sub UserForm_Initialize()
optSara.Value = True
End Sub
Private Sub FillBookmark(bkNm As String, bkVal As String)
Dim oRg As Range
With ActiveDocument
If Not .Bookmarks.Exists(bkNm) Then
MsgBox bkNm & " does not exist"
Exit Sub
End If
Set oRg = .Bookmarks(bkNm).Range
oRg.Text = bkVal
.Bookmarks.Add Name:=bkNm, Range:=oRg
End With
Set oRg = Nothing
End Sub
The "value" of each option button can be True or False. (To make sure only
one of them can be True at any time, in the graphical designer you display
the Properties pane; fill in the GroupName property with the same value for
all the option buttons.) The If ... ElseIf ... series in the cmdOK_Click
procedure determines which one is true and puts the corresponding text into
the bookmarks.
Here are some articles to help you understand what's being done here:
http://www.word.mvps.org/FAQs/MacrosVBA/ProcArguments.htm
http://www.word.mvps.org/FAQs/MacrosVBA/InsertingTextAtBookmark.htm
I'd recommend that if you have more than three option buttons, you should
replace them with a listbox or a combobox. That, unfortunately, requires
still a different way of determining what the user chose.
--
Regards,
Jay Freedman
Microsoft Word MVP FAQ:
http://word.mvps.org
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.