Which field is the cursor in? (ms word, vba)

In a VBA Word macro, I would like to get a Field

-object for the field containing the cursor.

enter image description here

The obvious attempt fails:

Private Sub Try1()
    MsgBox Selection.Fields.Count
End Sub

      

The array is empty. Then I tried:

Private Sub Try2()
    Dim oRange As Range
    Set oRange = Selection.GoTo(What:=wdGoToField)
    MsgBox oRange
End Sub

      

The cursor does not move, the message is empty.

I can iterate over ActiveDocument.Fields

, compare the ranges and find the contained fields. But there is probably a simple straight forward way?

+3


source to share


1 answer


My current production code iterated over Document.Fields

:



Sub Test()
    Dim oField As Field
    Set oField = FindWrappingField(Selection.Range)
    If oField Is Nothing Then
        MsgBox "not found"
    Else
        MsgBox oField
    End If
End Sub

Private Function FindWrappingField(vRange As Range)
    Dim oField As Field
    Dim nRefPos As Long
    ' If selection starts inside a field, it also finishes inside.
    nRefPos = vRange.Start
    ' 1) Are the fields sorted? I don't know.
    '    Therefore, no breaking the loop if a field is too far.
    ' 2) "Code" goes before "Result", but is it forever?
    For Each oField In vRange.Document.Fields
        If ((oField.Result.Start <= nRefPos) Or (oField.Code.Start <= nRefPos)) And _
            ((nRefPos <= oField.Result.End) Or (nRefPos <= oField.Code.End)) Then
                Set FindWrappingField = oField
                Exit Function
        End If
    Next oField
    Set FindWrappingField = Nothing
End Function

      

+1


source







All Articles