Is the below code correct,
or is there a better more efficient way?
tend to take the "if it works, it works" view of software these days - in
other words, I can't tell you if your code is "correct". In this case I
would be inclined to test a few special cases, e.g. what if the field is
right at the beginning or end of a range, what if the text is an empty
string, perhaps check that leading/trailing spaces are retained, and if you
are dealing with "international" data, see what happens to unusual accented
characters.
Also, I have one more issue. That is in the header, there is a text box
field that I can not seem to figure out how to get access. When I use
your
example for accessing the header / footer, the text box never is
accessable.
Could you please shed some light on that for me also?
I think you have encountered the "may have trouble detecting some fields in
the graphics layer" problem I mentioned. I haven't checked this in detail
but I think if you access the appropriate header object (and I didn't realy
give you the complete story about that before) you will be able to get these
too, e.g. to inspect one such object
For Each s In
ActiveDocument.Sections(1).Headers(wdHeaderFooterFirstPage).Shapes
If s.Type = msoTextBox Then
For Each f In s.TextFrame.TextRange.Fields
If f.Type = wdFieldMergeField Then
' do whatever you need
End If
Next
End If
Next
End Sub
If you need to deal with multiple sections or multiple types of
header/footer, you'll need to wrap that in another suitable loop. My memory
of this is a bit dim, but I think Word actually finds some fields in more
than one of the collections being processed in these code snippets - in your
case that's probably not going to do any harm except maybe to performance.
If you do mange to work out a more precise algorithm that always works,
please do post it back here.
Peter Jamieson
and I don't know how to solve it. Is it possible in this case to convert
the text box to a frame that will do the same job (select the box and use
Fomat Text Box|Text Box|Convert to Frame).
Peter Jamieson