将 Word 书签导入 Excel

Importing Word Bookmarks to Excel

我正在尝试将 Word 书签导入所选 Word 文档中的特定 Excel 单元格。我有一个宏,它获取 excel 数据并将其填充到 Word 模板中。我还需要能够获取该 word 文档并将其导入回 Excel。这是我目前所拥有的:

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

我在 "ws.Range("H" & (nextRow.Row)).Value2 = wdDoc.Bookmarks("Named_Insured").Range 线上得到 "Run-Time:438 / Object doesn't support this property or method" .Value2

我在这里忽略了什么?

第 1 步:在 VBA window 中,点击 "Tools",然后点击 "References",确保 "Microsoft Word xx.0 Object Library" 旁边有一个复选框

第2步:将问题行改为-

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

第 3 步:将最后一行更改为-

ActiveDocument.Close SaveChanges:=False

您可以像这样使用书签。

Sub PushToWord()

Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
On Error Resume Next

    ActiveDocument.Variables("BrokerFirstName").Value = Range("B1").Value
    ActiveDocument.Variables("BrokerLastName").Value = Range("B2").Value
    ActiveDocument.Fields.Update

On Error Resume Next
objWord.Visible = True

End Sub

或者,直接使用 DocVariables。

Sub PushToWord()

Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next

objWord.ActiveDocument.variables("BrokerFirstName").Value = Range("BrokerFirstName").Value
objWord.ActiveDocument.variables("BrokerLastName").Value = Range("BrokerLastName").Value
objWord.ActiveDocument.variables("Ryan").Value = Range("Ryan").Value


objWord.ActiveDocument.Fields.Update

'On Error Resume Next
objWord.Visible = True

End Sub

顺便说一句,您 运行 这些代码示例来自 Excel,而不是来自 Word。