Reference: in line Textbox Control Dynamically

K

Kevin McDonald

I want to put several ActiveX textbox controls on a word
document. I need to be able to reference them
dynamically. For example: I put 3 textbox controls on a
document. They are Textbox1, Textbox2, and Textbox3. I
would like use a For loop like so...

For x = 1 to 3
txtbox = "Textbox" + Trim(Str(x))
'here I would reference the textbox control
next x.

How do I reference the textbox control dynamically in VBA?
 
M

Martin Seelhofer

Hi Kevin

You probably are looking for the InlineShapes-collection. However,
you cannot access its elements using a string as you wanted. Therefore,
you'll have to program your own workaround, e.g. something like
the following (you might have to correct the line breaks of my
posting):

Function getActiveXTextbox(doc As Document, name As String) As TextBox
Dim shp As InlineShape
Dim ctrl As TextBox
' look at all inlineshapes
For Each shp In doc.Range.InlineShapes
' only take a closer look at Control Objects
If shp.Type = wdInlineShapeOLEControlObject Then
' just consider textboxes
If TypeName(shp.OLEFormat.Object) = "TextBox" Then
' check for the name
Set ctrl = shp.OLEFormat.Object
' Note: A textbox inherits the Name-
' property from the Control-class
If ctrl.name Like name Then
Set getActiveXTextbox = ctrl
Exit Function
End If
End If
End If
Next
' if we come here, the function returns Nothing
End Function

Now, with that handy function, you can do exactly what you wanted:

Dim x As Long
Dim txtBox As TextBox

For x = 1 to 3
Set txtBox = getActiveXTextbox(ActiveDocument, "Textbox" & x)
' Handle the case where there is no such control
If Not txtBox Is Nothing Then
' now do whatever you like using the object variable txtBox
' e.g. Present its value-property
MsgBox txtBox.Value
' ... or the font it uses:
MsgBox "This textbox uses " & txtBox.Font.Name
End If
Next


Cheers,
Martin
 

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