![]() |
|
#3
|
||||
|
||||
|
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 |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
Creating a Macro in VBA where a Dropdown Box Populates Text Bookmarks below
|
roseheller | Word VBA | 5 | 02-23-2021 03:10 PM |
| Macro to hide/unhide text to call variable bookmarks | Dr. Z | Word VBA | 2 | 05-27-2017 08:20 PM |
Transfer word doc bookmarks to excel using macro
|
Bedsy | Word VBA | 4 | 03-15-2015 10:58 PM |
Form updating Bookmarks - writes to the bookmarks multiple times
|
PeterPlys | Word VBA | 13 | 01-14-2015 06:41 AM |
Macro to list all bookmarks
|
Marrick13 | Word VBA | 4 | 02-09-2012 08:00 PM |