Microsoft Office Tutorials and References
In Depth Information
Creating a Bookmark from a Selection
The following macro bookmarks the current selection in the document, using
the selected text as the bookmark name. If the selection is long, only the first
40 characters (maximum number of characters for a bookmark name) are used.
Invalid characters will be removed, according to the following rules:
Bookmark names may not begin with numbers. Any numbers at the
beginning of a selection are cut off from the bookmark name.
Punctuation, such as periods and commas, are not allowed and are
Spaces are replaced with underscores.
View the Appendix to learn how to store this procedure
in a Standard module.
Option explicit¶
' * * * * *¶
Const varName As String = "BookmarkCounter"¶
Const varDuplicateName As String _¶
= "DuplicateBookmarkCounter"¶
' * * * * *¶
Sub CreateBookmark()¶
'Variable declaration¶
Dim rng As Word.Range¶
Dim BookmarkName As String¶
Dim var As Word.Variable¶
'Check whether the document variable that stores¶
'a counter for bookmarks without content exists¶
If varExists(ActiveDocument, varName) = False Then¶
'If not, create it and assign it the value 1¶
ActiveDocument.Variables.Add _¶
Name:=varName, Value:="1"¶
End If¶
Set var = ActiveDocument.Variables(varName)¶
Set rng = Selection.Range¶
If Selection.Type = wdSelectionIP Then¶
'The user didn't select any text; a bookmark without¶
'content will be inserted with¶
'an incremented name txt#¶
'Calculate that name¶
BookmarkName = "txt" & var.Value¶
var.Value = CStr(CLng(var.Value) + 1)¶
'Alternately, a prompt can be displayed¶
'to ask the user for the name¶
'Uncomment the next two lines to use that method¶
'BookmarkName = InputBox( _¶
'No text is selected. Type in a bookmark name.")¶
'Get the bookmark name based on the selected text¶
Search JabSto ::

Custom Search