Range/bookmark problem

A

acjharms

The following code isn't working for me (Word2K, WinXP). No errors,
just not adding the bookmarks I want. Any ideas would be appreciated.

<code snip>
x = 0
Set brange = ActiveDocument.Bookmarks("backup").Range
For Each Paragraph In brange.Paragraphs
If InStr(Paragraph.Range.Text, "Serial/") = 0 Then
bmname = "ser" + Trim(Str(x))
Set newrange = Paragraph.Range
x = x + 1
nespa = InStr(newrange.Text, Chr(9)) - 1
ActiveDocument.Bookmarks.Add Name:=bmname,
Range:=Paragraph.Range(Start:=0, End:=nespa)
End If
Next
</code snip>


CONTENTS OF brange

Serial/[tab]date[tab]
324-33[tab]1/2/2006
z231/23[tab]1/23/2006
 
J

Jay Freedman

I think the major problems are in the Bookmarks.Add statement. First,
the Range method that takes Start and End parameters applies only to a
Document object (see the Help topic on "Range method"), not to an
arbitrary Range object. When it does apply, the Start and End values
are counted from the beginning of the document.

It also doesn't help that the variable Paragraph uses a keyword
(there's a Paragraph object type, referring to the contents of the
Paragraphs collection). That may have confused VBA a bit.

Try this version; I think it does a bit better.

Dim brange As Range, newrange As Range
Dim x As Long
Dim oPara As Paragraph
Dim bmname As String

x = 0
Set brange = ActiveDocument.Bookmarks("backup").Range
For Each oPara In brange.Paragraphs
If InStr(oPara.Range.Text, "Serial/") = 0 Then
bmname = "ser" + Trim(Str(x))
Set newrange = oPara.Range
x = x + 1
newrange.End = newrange.Start + _
InStr(newrange.Text, vbTab) - 1
ActiveDocument.Bookmarks.Add Name:=bmname, _
Range:=newrange
End If
Next

As part of defensive programming, you should also check newrange to
make sure it contains a vbTab before you continue; otherwise you'll
wind up with the End one character to the left of the Start, which
will put the bookmark at the end of the previous line.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 
A

acjharms

Thanks, that did the trick! (Though a fat-fingered extra 'w' in
'newrange' caused a forehead-to-desk moment ;-))
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top