将Word书签导入Excel

时间:2018-01-10 19:08:46

标签: excel excel-vba import ms-word bookmarks vba

我正在尝试将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

我得到"运行时间:438 /对象不支持此属性或方法"在线" ws.Range(" H"&(nextRow.Row))。Value2 = wdDoc.Bookmarks(" Named_Insured")。Range.Value2"

我在这里俯瞰什么?

2 个答案:

答案 0 :(得分:1)

步骤1:在VBA窗口中,单击“工具”,然后单击“引用”,并确保“Microsoft Word xx.0对象库”旁边有一个复选框

步骤2:将问题行更改为 -

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

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

ActiveDocument.Close SaveChanges:=False

答案 1 :(得分:0)

你可以像这样使用书签。

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运行。