简体   繁体   中英

Insert enclosing bookmarks at once with Word Vba

I want to add multiple enclosing bookmarks once.

Enclosing Bookmarks are not correct. I get "[january]february]march]", not [january][february][march].

Here is my beginner code...

Sub Execute()

    Dim arrayBookmarks()

    arrayBookmarks = Array("january", "february", "march")

    Call ManageBookmarks(arrayBookmarks)

End Sub


Function ManageBookmarks(arrayBookmarks() As Variant)

    ' Code to optimize ("With", "End With")

    Dim rangeBookmark As Range

    For i = LBound(arrayBookmarks) To UBound(arrayBookmarks)

        If ActiveDocument.Bookmarks.Exists(arrayBookmarks(i)) Then

            ' ... 

        Else

            ActiveDocument.Bookmarks.Add arrayBookmarks(i)

            Set rangeBookmark = ActiveDocument.Bookmarks(arrayBookmarks(i)).Range

            rangeBookmark.Text = arrayBookmarks(i) ' & vbLf ' line break is ideal 

            ActiveDocument.Bookmarks.Add arrayBookmarks(i), rangeBookmark

        End If

    Next i

End Function

Try:

Function ManageBookmarks(arrayBookmarks() As Variant)
' Code to optimize ("With", "End With")
Dim rangeBookmark As Range, i As Long
With ActiveDocument
    For i = LBound(arrayBookmarks) To UBound(arrayBookmarks)
        If .Bookmarks.Exists(arrayBookmarks(i)) Then
            ' ...
        Else
            Set rangeBookmark = .Range.Characters.Last
            rangeBookmark.Collapse wdCollapseEnd
            .Bookmarks.Add arrayBookmarks(i), rangeBookmark
            Set rangeBookmark = .Bookmarks(arrayBookmarks(i)).Range
            rangeBookmark.Text = arrayBookmarks(i) ' & vbLf ' line break is ideal
            .Bookmarks.Add arrayBookmarks(i), rangeBookmark
        End If
    Next i
End With
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM