PDA

View Full Version : Word VBA Bookmarks



armitaej
06-02-2011, 06:01 PM
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

gmaxey
06-02-2011, 08:01 PM
Does your selected text start with a letter A-z? Your code should work if it does.

Jay Freedman
06-02-2011, 08:06 PM
Also, the only characters allowed are letters, numbers, and underscores -- no punctuation, no tab characters.

gmaxey
06-02-2011, 08:16 PM
Much of what little I know Jay has taught me. This I forgot. Thanks Jay.

armitaej
06-03-2011, 03:22 PM
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


file:///C:/Users/Evan/AppData/Local/Temp/moz-screenshot-3.png

gmaxey
06-03-2011, 03:44 PM
Try:

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

armitaej
06-06-2011, 03:44 PM
Wow! Works great! Very nicely done. Thanks