光标在哪个字段中? (ms word,vba)

时间:2015-06-09 11:42:05

标签: ms-word word-vba

在VBA Word宏中,我想为包含光标的字段获取Field - 对象。

enter image description here

显而易见的尝试失败了:

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

数组为空。然后我试了一下:

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

光标不移动,消息为空。

我可以迭代ActiveDocument.Fields,比较范围并找到包含的fiels。但可能有一个简单的直接方式?

3 个答案:

答案 0 :(得分:1)

我当前的生产代码,迭代超过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 :(得分:0)

我遇到了同样的问题,我用下面的代码解决了:

Sub Test()
    NumberOfFields = Selection.Fields.Count
    While NumberOfFields = 0
        Selection.MoveRight Unit:=wdCharacter, Count:=1, Extend:=wdExtend
        NumberOfFields = Selection.Fields.Count
    Wend
End Sub

当然,我必须知道光标在一个字段中。 显然,当您选择向右延伸的范围时,将在某个时刻选择该字段。范围的结束不计算(它不使用字段范围)

答案 2 :(得分:0)

我使用此代码

Sub GetFieldUnderCursor()
Dim NumberOfFields As Integer
Dim oFld As Field
Dim TextFeld As String
Dim Typ As Integer
Dim pos As Integer
Dim NameOfField As String
'update field. Cursor moves after the field
Selection.Fields.Update
'select the field
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
'check if there is a field
NumberOfFields = Selection.Fields.Count
If NumberOfFields = 0 Then
    MsgBox "No field under cursor"
    Exit Sub
End If
Set oFld = Selection.Fields(1)
TextFeld = Trim(oFld.Code.Text)
Typ = oFld.Type '85 is DOCPROPERTY, 64 is DOCVARIABLE
If Typ = 85 Or Typ = 64 Then
    pos = InStr(15, TextFeld, " ")
    If pos > 0 Then
        NameOfField = Trim(Mid(TextFeld, 12, pos - 11))
        MsgBox NameOfField
    End If
End If

结束子