Search code examples
vbams-worduserform

VBA and Word: Cutting a TextBox name to match that of a Bookmark


I have a Word template with lots of Bookmarks assigned to certain places in it. I created a UserForm with TextBoxes to insert text into those places/Bookmarks.

The names of the Bookmarks and TextBoxes match, but the TextBoxes name have "TextBox_" added infront of them. I also figured out how to loop through all of the TextBoxes (e.g.) of a tab.

Now I wanted to cut the "TextBox_" from the TextBoxes name, while looping, and assign their values to the Bookmarks. I wanted to do this using

Replace(ctl.Name, "TextBox_", "")

But it wont work. Can somebody tell me what's wrong or help me find a solution? My head is empty right now...

Thanks in advance!

My code so far:

Private Sub apply_textboxes()

Dim ctl As Control

For Each ctl In Me.MultiTab1.Pages(Me.MultiTab1.Value).Controls

    If TypeName(ctl) = "TextBox" Then

        ActiveDocument.Bookmarks(Replace(ctl.Name, "TextBox_", "")) = ctl.Value

    End If

End Sub

(In my UserForm, a button is calling the apply_textboxes sub.)

PS: For some reason, my "Hi" from the beginning gets cut out. So "Hi everyone" from down here!


Solution

  • This should work:

    ActiveDocument.Bookmarks(Replace(ctl.Name, "TextBox_", "")).Range.Text = ctl.Value
    

    You need that .Range.Text