Search code examples
excelimportms-wordbookmarksvba

Importing Word Bookmarks to Excel


I am trying to import Word Bookmarks into specific Excel cells from a selected Word document. I have one macro that takes the excel data and fills it into a Word template. I need to also be able to take that word document and import it back into Excel. This is what I have so far:

Sub Import()
Dim wdDoc As Object
Dim wdFileName As Variant
Dim ws As Worksheet
Dim nextRow As Range

wdFileName = Application.GetOpenFilename("Word files,*.doc;*.docx", , _
"Browse for document") 'dialog box
    If wdFileName = False Then
        MsgBox "No File Selected."
        Exit Sub
    Else
        Set wdDoc = CreateObject("Word.Application")
        wdDoc.Visible = True
            On Error Resume Next
        wdDoc.Documents.Open Filename:=wdFileName
            On Error GoTo 0
        wdDoc.Documents(wdFileName).Activate
            On Error GoTo 0
    End If


With wdDoc 'start import

Set ws = ThisWorkbook.Sheets("Sheet1")
Set nextRow = Cells(Rows.Count, "B").End(xlUp).Offset(1)

ws.Range("H" & (nextRow.Row)).Value2 = wdDoc.Bookmarks("Bookmark1").Range.Value2

End With
wdDoc.Close SaveChanges:=False
End Sub

I'm getting "Run-Time:438 / Object doesn't support this property or method" on the line "ws.Range("H" & (nextRow.Row)).Value2 = wdDoc.Bookmarks("Named_Insured").Range.Value2"

What am I overlooking here?


Solution

  • Step 1: In the VBA window, click on "Tools" then "References" and make sure that there is a checkbox next to "Microsoft Word xx.0 Object Library"

    Step 2: Change the problem line to-

    ws.Range("H" & (nextRow.Row)).Value = _
    ActiveDocument.Bookmarks("Name_Insured").Range.Text
    

    Step 3: Change the last line to-

    ActiveDocument.Close SaveChanges:=False