Is it possible for VBA to determine if the insertion point is in a Word field? (Specifically, I'm looking for a REF field, but I know how to test for that once I get the field.)
I want to get the value of Code.Text of the current field, providing the cursor is in a field.
I have success with:
Set rng = Selection.range
sCode = rng.Fields(1).Code.Text
This fails, however, if field results are showing, and if the results are more than one word.
Maybe I missed a shortcut, but this actually seems a bit difficult when you start from the selection. It might be easier to cycle through the Fields collection and check whether the selection is in a field. But I didn't think of that before writing this...
' Make sure there is at least one field in this document
If ActiveDocument.Fields.Count = 0 Then Exit Sub
' Store selection
Dim strStartEnd As String
strStartEnd = Selection.Start & "|" & Selection.End
' Expand selection to encompass the field
If .Fields.Count > 0 Then Exit Do
If .Start > 1 Then .MoveStart wdWord, -1
If .End < ActiveDocument.Content.End - 1 Then .MoveEnd wdWord, 1
If .Start <= 1 And .End >= ActiveDocument.Content.End - 1 Then Exit Do
' Now do whatever with the field
' Restore selection
.Start = Split(strStartEnd, "|")(0)
.End = Split(strStartEnd, "|")(1)
I was expanding the range to wdWord, and that got only one word of the field if there were several. MoveStart and MoveEnd works well.
I think this might be better:
' Check for fields in the selection
If .Fields.Count > 0 Then
' Check fields collection for a field that contains the selection
Dim fld As Word.Field
For Each fld In ActiveDocument.Fields
' Compare Selection.Start position to field Start and End
If .Start >= fld.Result.Start And .Start <= fld.Result.End Then
If Not fld Is Nothing Then Set fld = Nothing
The documents in question could have hundreds of field codes. Instead of looping through ActiveDocument.Fields, I can expand Selection.Range to the current paragraph, and then loop through each field in that much smaller range.
Thank you for your help.
You might want to take a look at the macros posted by Jefferson and Andrew77 at:
both posts include macros to convert all fields in the selected range to textual representations - including nested fields. From memory, the results are copied to the clipboard, from where you can simply paste them wherever you want.