new range bounds form another range

F

f.tecnig

Hi,
I would like to know if it's possible to easily create a new range following
a previously created range

What I want is to select a table which is located after a bookmark

Sub TestTbl()
Dim doc As Document
Dim rng1 As Range
Dim rng2 As Range

Set doc = activeDocument
Set rng1 = doc.Bookmarks("TableF").Range

'Error
'Set rng2 = doc.Range(Start:=rng1.End, End:=0)
Set rng2 = doc.Range(Start:=1, End:=2)
rng2.MoveEnd Unit:=wdTable
rng2.Font.Color = wdColorRed
End Sub

Maybe copying rng1 to rng2 and then modifying rng2 is a better option if I
want a new range
 
J

Jay Freedman

When you use the syntax doc.Range(Start:=number, End:=number), the numbers
are absolute character counts from the beginning of the document, which is
not what you want. You sort of had the right idea in the commented-out line
with Start:=rng1.End, but then the End:=0 caused an error. This variation
works (the Collapse method makes the Start and End values of the range both
equal to the original End value):

Sub x1()
Dim doc As Document
Dim rg As Range

Set doc = ActiveDocument
Set rg = doc.Bookmarks("TableF").Range
rg.Collapse wdCollapseEnd
rg.MoveEnd unit:=wdTable
rg.Font.Color = wdColorRed
End Sub

A different way to go about this, which will work even if the bookmark isn't
immediately before the table, is this.

Sub x2()
Dim doc As Document
Dim rg As Range

Set doc = ActiveDocument
Set rg = doc.Bookmarks("TableF").Range
While Not rg.Information(wdWithInTable)
rg.Move unit:=wdCharacter
Wend
Set rg = rg.Tables(1).Range
rg.Font.Color = wdColorRed
End Sub

Note that if a range is completely inside a table, then the range's
..Tables(1) property refers to that entire table, not to the first table of
the document -- that would be doc.Tables(1) instead of rg.Tables(1).

In either case, you really need some error-checking to make sure that the
bookmark exists (use doc.Bookmarks.Exists("TableF") to determine this) and
to make sure there is a table after it (this is more complicated).

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

f.tecnig

Thanks
i used
While Not rng.Information(wdWithInTable)
rng.MoveStart unit:=wdParagraph
Wend

to avoid excesive iterations because the table should be after a paragraph
in the document
 

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