2015-06-09 147 views
3

在VBA Word宏中,我想为包含光标的字段获取一个Field对象。光标在哪个字段? (ms word,vba)

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。但可能有一个简单的直接方式?

+0

fields'你的文档中有什么样的'? –

+0

@KazimierzJawor类型是'DOCPROPERTY'。 – olpa

+0

我检查了一些没有用的选项,例如。我在一些情况下检查了这个代码'Selection.Expand wdWord'选择整个字段,但它不是一个规则。看来你需要使用循环来确保你在现场。 –

回答

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 
+0

事情比预期更复杂。如果代码位于“不在文档中”,代码不会找到该字段,因此在页眉,页脚,文本框或类似内容中。对于这种情况,我现在使用更多的循环。外层的是'vRange.Document.StoryRanges',下一层是'.NextStoryRange',最嵌套的是'.Fields'。另外我还将当前的故事与参考故事进行比较。 – olpa