PDA

View Full Version : Insert and Name Bookmark



rockwellsba
10-22-2009, 12:05 PM
Hello. Does anyone know of a VBA code to automatically insert a bookmark after each colon in a Word2007 document and have VBA name the bookmarks "BM1", "BM2", 'BM3", etc.? Any help is most appreciated.

Tinbendr
10-22-2009, 02:42 PM
Sub AddBookmarkAfterColon()
Dim Rng As Range
Dim BM_Num As Integer
Dim MyCount As Integer
Set Rng = ActiveDocument.Range(0, 0)
With Rng
Do
MyCount = .MoveStartUntil(":")
If MyCount > 0 Then
.MoveStart wdCharacter
BM_Num = BM_Num + 1
.Bookmarks.Add "BM" & BM_Num
End If
Loop While MyCount > 0
End With
End Sub

rockwellsba
10-22-2009, 03:31 PM
Tinbendr-
Worked like a charm. Thank you VERY much. You are awesome.

fumei
10-23-2009, 09:29 AM
An alternative:
Option Explicit

Sub AfterColon()
Dim r As Range
Dim j As Long

Set r = ActiveDocument.Range
j = 1
With r.Find
Do While .Execute(Findtext:=":", Forward:=True) _
= True
With r
.Collapse 0
ActiveDocument.Bookmarks.Add Name:="BM" & j, _
Range:=r
.Collapse 0
End With
j = j + 1
Loop
End With
End Sub

rockwellsba
10-23-2009, 03:03 PM
Fumei- Thanks.

fumei
10-26-2009, 11:59 AM
There is almost always more than one way to skin a VBA cat. Generally speaking, I try to avoid counters, although tinbendr's:
MyCount = .MoveStartUntil(":")
is rather innovative.

Just want to point out that:
Dim MyCount As Integer
is passe. VBA automatically converts all Integer to Long. Automatically, without asking. While insignificant in terms of processing resources (although not nil...it still does have to parse the code and convert them), most VBA coders no longer declare As Integer. Why bother? They are all converted to Long anyway.