1

我正在编写一个 VBA 宏来仅更新 Word 2013 文档中的 SEQ 字段。我将它设计为使用 GoTo 从文档的开头到结尾一次访问每个 SEQ 字段(不更新全部),以确保我跳过其他字段类型。我正在努力让它为每个 SEQ 字段循环,直到到达文档的末尾。我希望它可以在任何文档中工作,无论书签或其他结束标记如何。

这是我到目前为止的代码(带注释):

ActiveWindow.View.FieldShading = wdFieldShadingAlways '转到文档顶部 Selection.HomeKey Unit:=wdStory '转到第一个 SEQ 字段

Selection.GoTo What:=wdGoToField, Which:=wdGoToNext, Count:=1, Name:="SEQ"

' 选择.查找.清除格式

'只要域码多,就更新这一项,然后转到下一项 Do While Selection.GoToNext.wdGoToField = True Selection.Fields.Update Loop

4

1 回答 1

1

It's a bit late, but your question came up when I was looking for the same answer. :-)

For flexibility, the actual work is done as a function, where the field code is received as a string. That way I can call the function with any desired field code, not necessarily a specific SEQ or any field code at all.

Function UpdateSpecificFields(MyFieldCode As String)

Dim MyField As Field

    For Each MyField In ActiveDocument.Fields

'        Debug.Print """" & MyField.Code & """" & MyField.Result

        If InStr(1, MyField.Code, MyFieldCode) <> 0 Then
            MyField.Update
        End If

    Next MyField

End Function

We're looping through all the fields within the active document. You could include a test of whether MyField.Type = wdFieldSequence to reduce the unnecessary work.

The InStr is there in case of odd spacing; sometimes the field creator might include an extra space before or after the code itself, so I didn't want to be too literal. (I suppose there should have been a trim() to get rid of said spaces but I was getting a little lazy.)

Usage: Call the function from a sub.

Sub UpdateSEQQs()
    UpdateSpecificFields ("SEQ Qs")
End Sub

I have a SEQ called Qs, so you can see how it was called above. Hope this helps someone!

于 2018-06-29T14:33:20.793 回答