Operations on text which includes field codes

T

Tony Gravagno

Word 2003 SP1
If I have Selection.Start = x and Selection.End = y, the
Selection.Text doesn't properly operate on data if that Range includes
fieldcodes.

Please try the following:
In a new document put the letters "abcd"
Now after 'b', insert a Date fieldcode.
Now add and run this macro:

Private Declare Sub Sleep Lib "kernel32" _
(ByVal dwMilliseconds As Long)
Private Sub try()
Dim doc As Word.Document
Dim pos As Integer
Set doc = Application.ActiveDocument
Debug.Print Len(doc.Range.Text)
For pos = 0 To Len(doc.Range.Text)
doc.Range(pos, pos + 1).Select
Selection.Font.Color = wdColorRed
Sleep 500
Next pos
End Sub

Notice:
1) 'a' goes red on 0, 'b' on 1, the entire date goes red on '2'.
2) 'c' is never reached, even if the For loop is set to Len+2 or
doc.Characters.Count, etc.

Try toggling the field code to get this text:
ab{ DATE \* MERGEFORMAT }cd
Then re-run (change color to Blue to see the diff between runs).
Note that the selection goes through each character of the field code
but stops at the "}". By adding more characters to the end of the
string ('cdexxxxxxxxxxxxxxxxxz') and setting the Range end from pos+1
to pos+20, somehow the routine above eventually runs through the whole
string.

My application: I have a Selection of text and I know that at the end
of the selection there should be some specific character, but when I
look at the end of the selection I may or may not see these characters
if the selection happens to include a field. I don't want to code a
cludge around this - any ideas?

Thanks.
Tony
 
K

Klaus Linke

Hi Tony,

Most fields have both code and a result, and you have to add both.

a{ date }bcd¶
a12.02.2005bcd¶

Set doc = Application.ActiveDocument
Debug.Print Len(doc.Range.Text)
15
Debug.Print doc.Range.End - doc.Range.Start
24
Debug.Print doc.Fields(1).Code.Start, doc.Fields(1).Code.End
2 8
Debug.Print doc.Fields(1).Result.Start, , doc.Fields(1).Result.End
9 19

Regards,
Klaus
 

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