-
Word VBA Bookmarks
Hi. I am new with VBA. I am trying to create VBA code that automatically generates a bookmark. The name of the bookmark will be the selected text (with spaces removed). The code I have created looks like this:
Sub AutoBookmark()
Dim noSpace As String
Selection.Copy
noSpace = Replace(Selection.Text, " ", "")
With ActiveDocument.Bookmarks
.Add Range:=Selection.Range, Name:=noSpace
.DefaultSorting = wdSortByName
.ShowHidden = False
End With
End Sub
I get an error when running the code saying "bad bookmark name". Does anyone have any suggestions?
Thanks
-
Does your selected text start with a letter A-z? Your code should work if it does.
-
Also, the only characters allowed are letters, numbers, and underscores -- no punctuation, no tab characters.
-
Much of what little I know Jay has taught me. This I forgot. Thanks Jay.
-
I realized what I was doing wrong. say I had the following text: To Top
and wanted to use my autobookmark macro. When I highlighted the text, I unintentionally highlighted the two spaces directly after the "p" in top, which isnt just a space, I guess it is a paragraph, which is considered an object, not a string?
So the code does work, it is just not very robust... any suggestions for improvement? It would be nice if I could code it to just pick out the letters of a selected text and make a bookmark based on that. That way I wouldn't need to worry about symbols or numbers.
Thanks guys
[IMG]file:///C:/Users/Evan/AppData/Local/Temp/moz-screenshot-3.png[/IMG]
-
Try:
[VBA]Option Explicit
Sub BookmarkSelectedText()
Dim oStr As String
ActiveDocument.Bookmarks.Add MakeValidBMName(Selection.Range.Text), Selection.Range
End Sub
Function MakeValidBMName(strIn As String)
Dim pFirstChr As String
Dim i As Long
Dim tempStr As String
strIn = Trim(strIn)
pFirstChr = Left(strIn, 1)
If Not pFirstChr Like "[A-Za-z]" Then
strIn = "A_" & strIn
End If
For i = 1 To Len(strIn)
Select Case Asc(Mid$(strIn, i, 1))
Case 49 To 58, 65 To 90, 97 To 122
tempStr = tempStr & Mid$(strIn, i, 1)
Case Else
tempStr = tempStr & "_"
End Select
Next i
tempStr = Replace(tempStr, " ", " ")
MakeValidBMName = tempStr
End Function
[/VBA]
-
Wow! Works great! Very nicely done. Thanks
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules