View Single Post
  #3   Report Post  
Jezebel
 
Posts: n/a
Default

The search range is effectively a hidden property of the Find object. The
reference is created when the Find object is instantiated (ie, either the
Selection or the Range of which the object is a property), and is not then
changed. So while the range referenced by oRg is redefined with each
iteration, the base range through which Find is progressing, is not.

The displayed text of a field is its Result. So you could use

oRg.Fields(1).Result


Seperately, as a matter of good programming practice, when you declare
object variables you should specify the library they belong to --

Dim oRg As Word.Range
Dim fldPg As Word.Field

It costs nothing to do this, and it will save you grief when you start
referencing other libraries (like Excel) in your projects. There are many
libraries that have Range and Field objects, and they are not
interchangeable.




"Max Moor" wrote in message
6...
Hi All,
I'm trying to learn enough about Range objects and Find (et. al.)
to do some reformatting of a long document. I got the code below from
Jay, and it works like a charm, but I don't grasp how entirely.

I understand that if I use Find on a Range object, the range
object is redefined if the Find is successful. In the code below, the
oRg range is originally set to the whole document. When the Find
executes, it appears that the oRg Start and End are redefined to bound
just the reference field found.

I expected that only the start point of the range would be
redefined, but oIns is a duplicate of it. When oIns is collapsed to its
end, it's the end of the field found, not the end of the document.

So... if oRg has been redefined to bound only the found field,
how does Find get beyond that range to find the next matching field,
later in the document, on the next loop???

Also, given the code below, how can I access the text of the field
that is found? The variable strCode is set to the reference code
itself, with brackets and big numbers. I want to get the text that is
actually visible in the document. In my case, it's the name of a
header. Ho do I get to that?

Thanks, Max




Sub AddPageNumberRefs()
Dim oRg As Range
Dim oIns As Range
Dim strCode As String
Dim fldPg As Field

Set oRg = ActiveDocument.Range
oRg.TextRetrievalMode.IncludeFieldCodes = True
With oRg.Find
.Forward = True
.Format = True
.Style = ActiveDocument.Styles("Cross-reference Char")
.Text = "^d REF"
Do While .Execute
strCode = oRg.Fields(1).Code.Text
Set oIns = oRg.Duplicate
With oIns
.Collapse wdCollapseEnd
.Text = ", pg "
.Collapse wdCollapseEnd
Set fldPg = ActiveDocument.Fields.Add(Range:=oIns, Type:
=wdFieldEmpty)
fldPg.Code.Text = " PAGE" & LTrim(strCode)
fldPg.Update
End With
Loop
End With
End Sub