Search code examples
excelvbams-worduserformbookmarks

VBA/Userform - Transfer Value from a TextBox to Word with Bookmarks don't work


I'm trying to create a userform that transfers the values of TextBoxes to a bookmarked location in a Word file but I'm getting an error. I tried some examples which I found on Google but I still getting the error.

I get the Error "VBA Object Doesn’t Support this Property or Method Error (Error 438)"

Am now at this point where I'm just trying a shorter macro which opens the Word file and should write "Test" into one bookmark:

Private Sub CommandButton3_Click()
Dim wordApp As Object
Dim wordDoc As Object
VorlagePfad = "D:\Temp\Testfile.doc"
DisplayAlerts = False
Set wordApp = CreateObject("word.application")
wordApp.Options.SaveInterval = 0

wordApp.Visible = True
Set wordDoc = wordApp.documents.Open(Filename:=VorlagePfad)

With wordDoc.Selection
    .Bookmarks("Zeile1").Range.Text = "Test"
End With

End Sub

The error ocures at the line

With wordDoc.Selection

I also tried this code and got also the same error:

Private Sub CommandButton3_Click()
Dim wordApp As Object
Dim wordDoc As Object
VorlagePfad = "D:\Temp\Testfile.doc"
DisplayAlerts = False
Set wordApp = CreateObject("word.application")
wordApp.Options.SaveInterval = 0
wordApp.documents.Open VorlagePfad
wordApp.Visible = True
Set wordDoc = wordApp.documents.Open(Filename:=VorlagePfad)

wordApp.Bookmarks("Zeile1").Range.Text = "Test"

End Sub

I hope you can help me.

Kind regards


Solution

  • You just need to remove the ".Selection". Like this:

    Private Sub CommandButton3_Click()
    Dim wordApp As Object
    Dim wordDoc As Object
    VorlagePfad = "D:\Temp\Testfile.doc"
    DisplayAlerts = False
    Set wordApp = CreateObject("word.application")
    wordApp.Options.SaveInterval = 0
    
    wordApp.Visible = True
    Set wordDoc = wordApp.documents.Open(Filename:=VorlagePfad)
    
    With wordDoc
        .Bookmarks("Zeile1").Range.Text = "Test"
    End With
    
    End Sub