Thread: [Solved] Macro for creating bookmarks
View Single Post
 
Old 07-10-2025, 04:36 PM
Guessed's Avatar
Guessed Guessed is offline Windows 10 Office 2016
Expert
 
Join Date: Mar 2010
Location: Canberra/Melbourne Australia
Posts: 4,176
Guessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant futureGuessed has a brilliant future
Default

Paul posted a good solution while I was playing with this. I did find a clean Regex method to make the bookmark name safe so I'll add my solution anyway. I didn't consider table cells and didn't do any testing with tables so Paul's solution may be a better fit for you.
Code:
Sub AddBookmarksMyStyle()
  Dim aRng As Range, sBk As String
  Set aRng = ActiveDocument.Range

  With aRng.Find
    .ClearFormatting
    .Style = ActiveDocument.Styles("myStyle")
    .Replacement.ClearFormatting
    .Text = ""
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchKashida = False
    .MatchDiacritics = False
    .MatchAlefHamza = False
    .MatchControl = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    Do While .Execute = True
      sBk = MakeValidBookmarkName(aRng.Text)
      ActiveDocument.Bookmarks.Add Name:=sBk, Range:=aRng
      aRng.Collapse Direction:=wdCollapseEnd
    Loop
  End With
End Sub

'---------------------------------------------------------
Function MakeValidBookmarkName(ByVal inputName As String) As String
  Dim regex As Object
  Set regex = CreateObject("VBScript.RegExp")
  regex.Pattern = "[^a-zA-Z0-9_]"  ' Define pattern to match invalid characters (anything not alphanumeric or underscore)
  regex.Global = True
  MakeValidBookmarkName = regex.Replace(inputName, "_")  ' Replace invalid characters with underscore
  If IsNumeric(Left(MakeValidBookmarkName, 1)) Then  ' Solve if name starts with number
    MakeValidBookmarkName = "BM_" & MakeValidBookmarkName
  End If
End Function
__________________
Andrew Lockton
Chrysalis Design, Melbourne Australia
Reply With Quote