Selecting a range on a certain Page

J

John

Hello,
I am new to VBA with Word. Can someone tell me how I would select a certain
range on a specific page. For example, I am using the following to select a
range (from character 81 to the next tabstop). This seems to work fine but
only on the 1st page of my document. How can I select this range on another
page, for example page 20?

Any help would be greatly appreciated! Thanks!


Set myRng = ActiveDocument.Range(Start:=81, End:=82)
myRng.Select

Do Until myRng = oChar

If myRng <> oChar Then
Pos = Pos + 1
Set myRng = ActiveDocument.Range(Start:=Pos, End:=Pos + 1)
myRng.Select
End If

Loop
Set myRng = ActiveDocument.Range(Start:=81, End:=Pos)
 
J

Jezebel

Not sure what you're getting at here. Ranges and pages are not directly
related. The body of the document is one big range, from Start = 1 to
whatever. If page 20 starts at position 593, then Range(Start:593, End:=594)
will refer to the first character on page 20.

You don't need to select the range to check its characters. In the code
snippet you give, the Select statements are irrelevant, apart from the last
one.

You don't need to redefine the range each time you iterate your loop: you
can simply reset range's start and end properties:

MyRange.Start = pos
MyRange.End = pos + 1


You can use the MoveEndUntil method to find the character you want in one
go:

With ActiveDocument.Range(Start:=81, End:=81)
.MoveEndUntil oChar
.End = .End + 1
.Select
End with
 
J

John

Ok,
Thanks! But how can you tell what the starting character is for a given
page? In other words, how do you know what position page 20 starts at?

THANKS!
 
F

fumei

Well, if you need to know the actual integer of the first character of any
page, you must go there first. This is because "page" is a dynamic object.
So:

' go to whatever page - 20 in this example
Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext, Name:="20"
' uses the pre-defined bookmark "page" to get the Range.Start
' this is a Long Integer
MsgBox ActiveDocument.Bookmarks("\page").Range.Start

So, for example, if for some reason or other, you wanted to know how many
characters were on a specific page:

Dim lngStart As Long
Dim lngEnd As Long

Selection.GoTo What:=wdGoToPage, Which:=wdGoToNext, Name:="20"
lngStart = ActiveDocument.Bookmarks("\page").Range.Start
lngEnd = ActiveDocument.Bookmarks("\page").Range.End
MsgBox "This page starts at character number " & _
lngStart & " and ends at " & _
lngEnd & ", for a total of " & _
(lngEnd - lngStart) & " characters, including spaces."
 

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