Userform TextBoxes

C

Chris Brunt

I have a userform with 14 text boxes. I am trying to put
the text entered into each textbox into 14 { DOCVARIABLE }
fields in a document. The code:
For n = 1 To 14
ActiveDocument.Variables("Textbox" & n).Value = TextBox &
n.Text
Next n
does not work. Please help.
Regards
Chris Brunt
 
D

Doug Robbins - Word MVP

Hi Chris,

Rather that doing this, I would suggest that you give each TextBox and the
corresponding variable a meaningful name. However, if you want to make it
difficult for yourself<g>, use:

Dim n As Integer, myvar As String, mycontrol As Control
For n = 1 To 14
myvar = "TextBox" & n
For Each mycontrol In UserForm1.Controls
If mycontrol.Name = "TextBox" & n Then
ActiveDocument.Variables(myvar).Value = mycontrol.Text
End If
Next mycontrol
Next n
ActiveDocument.Fields.Update


--
Please respond to the newsgroups for the benefit of others who may be
interested.

Hope this helps
Doug Robbins - Word MVP
 
J

Jay Freedman

Hi, Chris,

I suppose that Doug, being in Oz, has headed off to bed now so I'll pick up
the thread.

His concern is that some time from now, having been away from the code for a
while, you're going to need to do some maintenance. You'll look at it,
scratch your head, and say "What the heck is TextBox12?" If the names of the
box and the corresponding document property are PostalCode, there's no
difficulty.

Although at first sight you might think you'd have to throw away the loop
structure and handle each textbox separately, you can simply load an array
with the names and iterate through that:

Dim n As Integer, myvar As String, mycontrol As Control
Dim NameArray As Variant
NameArray = Array("FirstName", "LastName", "StreetAddress", .... )
' fill this up with your 14 names

For n = 0 To UBound(NameArray)
myvar = NameArray(n)
For Each mycontrol In UserForm1.Controls
If mycontrol.Name = myvar Then
ActiveDocument.Variables(myvar).Value = mycontrol.Text
End If
Next mycontrol
Next n
ActiveDocument.Fields.Update

Notice the change in the "For n" statement -- unless you use an Option Base
1 statement, arrays are numbered from 0, not 1. The UBound function figures
out the last index of the array, so you don't have to keep track of how many
names you added.
 
D

Doug Robbins - Word MVP

Thanks for chirping in Jay.

Please respond to the newsgroups for the benefit of others who may be
interested.

Hope this helps
Doug Robbins - Word MVP
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top