Using VBA to work with a field including the curly brackets, notjust the code or result

D

David Beamish

I am creating Word documents with lots of clickable hyperlinks (mostly
internal cross-references, table of contents, etc.) and I want to colour
the hyperlinks so that they are easily visible on-screen. I tried a
macro on these lines:

Dim oField As Field
For Each oField In ActiveDocument.Fields
If oField.Type = wdFieldHyperlink Or oField.Type = wdFieldRef _
Or oField.Type = wdFieldPageRef Then
oField.Result.Font.Color = wdColorBlue
End If
Next oField

The problem is that this affects only the part of the field within the
curly brackets, and when the field is updated the formatting disappears.
I can get round it like this:

Dim oField As Field
For Each oField In ActiveDocument.Fields
If oField.Type = wdFieldHyperlink Or oField.Type = wdFieldRef _
Or oField.Type = wdFieldPageRef Then
oField.Select
Selection.Font.Color = wdColorBlue
End If
Next oField

But this is much slower and seems rather inelegant. Does anyone know any
way in VBA of operating on a range which includes the whole of a field,
curly brackets and all, other than selecting it?
 
S

Stefan Blom

For the hyperlinks you could just apply the Hyperlink character style
(modified to suit your needs):

For Each f In ActiveDocument.Fields
If f.Type = wdFieldHyperlink Then
f.Result.Style = wdStyleHyperlink
End If
Next f

For the REF and PAGEREF fields, format the field code and add the \*
CHARFORMAT switch, which ensures that the formatting is preserved when
updating:

Dim oField As Field
For Each oField In ActiveDocument.Fields
If oField.Type = oField.Type = wdFieldRef _
Or oField.Type = wdFieldPageRef Then
oField.Code.Font.Color = wdColorBlue
oField.Code.Text = oField.Code.Text & _
" \* CHARFORMAT"
oField.update
End If
Next oField

Note that the above code does not test for the presence of the \*
CHARFORMAT switch in the field code, which means that it will be added
several times if the macro is run several times. Adding an IF
statement which uses Instr to test for "CHARFORMAT" would take care of
that.

--
Stefan Blom
Microsoft Word MVP


in message
news:%[email protected]...
 

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