我当前的代码删除了单词中的书签,有没有办法保留书签?

时间:2019-04-24 16:26:39

标签: vba ms-word

我有一个代码,可将数据从电子表格复制到特定文档的特定书签中。运行它时,它可以正常工作,但是书签已从电子表格中删除。有没有办法将书签保留在文档中

Dim ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Sheet6")

    Set objWord = CreateObject("Word.Application")

    objWord.Visible = True

    objWord.Documents.Open "C:\GR1 CPA Test1.docx" ' change as required

    With objWord.ActiveDocument
        .Bookmarks("CN1").Range.Text = ws.Range("C25").Value
        .Bookmarks("CN2").Range.Text = ws.Range("C25").Value
        .Bookmarks("CNo").Range.Text = ws.Range("C26").Value
        .Bookmarks("CL1").Range.Text = ws.Range("C27").Value
        .Bookmarks("Ex1").Range.Text = ws.Range("C28").Value
        .Bookmarks("Ex2").Range.Text = ws.Range("C28").Value
        .Bookmarks("Su1").Range.Text = ws.Range("C29").Value
        .Bookmarks("Su2").Range.Text = ws.Range("C29").Value
        .Bookmarks("Su3").Range.Text = ws.Range("C29").Value

    .Save
    .Close

    End With

    Set objWord = Nothing


End Sub

1 个答案:

答案 0 :(得分:0)

我过去曾经使用过它:

'Replace the text in a bookmark or insert text into an empty (zero-length) bookmark
Sub SetBookmarkText(oDoc As Word.Document, sBookmark As String, sText As String)

    Dim BMRange As Word.Range

    If oDoc.Range.Bookmarks.Exists(sBookmark) Then
      Set BMRange = oDoc.Range.Bookmarks(sBookmark).Range
      BMRange.Text = sText
      oDoc.Range.Bookmarks.Add sBookmark, BMRange
    Else
      MsgBox "Bookmark '" & sBookmark & "' not found in document '" & oDoc.Name & "'" & _
              vbCrLf & "Content not updated"
    End If

End Sub

用法:

    Dim ws As Worksheet, doc as object

    Set ws = ThisWorkbook.Sheets("Sheet6")

    Set objWord = CreateObject("Word.Application")

    objWord.Visible = True

    Set doc = objWord.Documents.Open("C:\GR1 CPA Test1.docx")

    SetBookmarkText doc, "CN1", ws.Range("C25").Value
    SetBookmarkText doc, "CN2", ws.Range("C25").Value
    'etc etc

    doc.Save
    doc.Close
    Set objWord = Nothing

End Sub