如何更新除目录之外的所有字段

问题描述 投票:0回答:1

我正在尝试创建一个宏,有 3 种不同的选择来更新 Word 文档中的字段。我能够更新所有字段,包括目录和链接或仅更新目录,但也希望能够仅更新目录以外的字段。有没有办法选择除目录之外的所有内容然后更新?这是我正在运行的当前代码:

Sub RefreshFields()
'
' RefreshFields Macro
'
'
    Dim ToC As TableOfContents

    Select Case InputBox("Update which fields?" & vbCrLf & "Type '1' for all fields" & vbCrLf & "Type '2' for Table of Contents only" & vbCrLf & "Type '3' for all fields except Table of Contents")
    
    Case 1
        Selection.WholeStory
        Selection.Range.HighlightColorIndex = wdYellow
        Selection.Fields.Update
        MsgBox ("All fields updated")
        
    Case 2
        For Each ToC In ActiveDocument.TablesOfContents
        ToC.Update
        Next
        MsgBox ("Only ToC updated")
        
    Case 3
'
'
'        MsgBox ("All fields except ToC updated")

    End Select
    
End Sub

我尝试了不同的功能来选择目录并将其与某种“例外”功能配对,但无法做到。

vba ms-word tableofcontents
1个回答
0
投票
  • 利用用户定义函数 (UDF) IsFieldInTOC 确定该字段是否存在于目录 (TOC) 中。
Option Explicit

Sub RefreshFields()
    Dim fld As Field
    
    Select Case InputBox("Update which fields?" & vbCrLf & "Type '1' for all fields" & vbCrLf & "Type '2' for Table of Contents only" & vbCrLf & "Type '3' for all fields except Table of Contents")
        Case 1
            Selection.WholeStory
            Selection.Range.HighlightColorIndex = wdYellow
            Selection.Fields.Update
            MsgBox ("All fields updated")
        Case 2
            Dim ToC As TableOfContents
            For Each ToC In ActiveDocument.TablesOfContents
                ToC.Update
            Next
            MsgBox ("Only ToC updated")
        Case 3
            For Each fld In ActiveDocument.Fields
                If Not IsFieldInTOC(fld) Then
                    fld.Update
                End If
            Next
            MsgBox ("All fields except ToC updated")
    End Select
End Sub

Function IsFieldInTOC(fld As Field) As Boolean
    Dim ToC As TableOfContents
    Dim fldStart As Long
    Dim fldEnd As Long
    fldStart = fld.Result.Start
    fldEnd = fld.Result.End
    For Each ToC In ActiveDocument.TablesOfContents
        If (fldStart >= ToC.Range.Start And fldStart <= ToC.Range.End) _
            Or (fldEnd >= ToC.Range.Start And fldEnd <= ToC.Range.End) Then
            IsFieldInTOC = True
            Exit Function
        End If
    Next ToC
    IsFieldInTOC = False
End Function
© www.soinside.com 2019 - 2024. All rights reserved.