【问题标题】:Function fails when document is changed in MS Word when generating Table of Content生成目录时在 MS Word 中更改文档时功能失败
【发布时间】:2020-10-13 20:56:20
【问题描述】:

''' 当我使用下面的代码时,它可以在创建它的文档中使用。如果我更改文件,它会失败。有谁知道为什么? '''

'
Sub AddTOC() 'Need to find how to stop going in error on doc change
    Selection.GoTo What:=wdGoToLine, Which:=wdGoToAbsolute, Count:=0
        Application.Templates( _
        "C:\Users\Sean Celestin\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In 
Building Blocks.dotx" _
        ).BuildingBlockEntries("Automatic Table 1").Insert Where:=Selection.Range _
        , RichText:=True
        
        Selection.InsertBreak Type:=wdPageBreak
End Sub

'

【问题讨论】:

    标签: vba ms-word tableofcontents


    【解决方案1】:

    下面的代码基本上做同样的事情,但没有将目录嵌入到 Building Block Entry 使用的容器中。更新 TOC 时,该容器会对性能造成重大影响。通过不使用 Selection,代码也更加高效。

    Sub AddTOC()
    Application.ScreenUpdating = False
    With ActiveDocument
      .Range(0, 0).Text = vbCr & Chr(12)
      .Fields.Add .Range(0, 0), wdFieldEmpty, "TOC \o ""1-3"" \h \z \u", False
      .Range(0, 0).Text = "Contents" & vbCr
      .Range.Paragraphs.First.Style = "TOC Heading"
    End With
    Application.ScreenUpdating = True
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 2012-09-20
      • 2014-07-24
      • 2015-06-06
      • 2021-09-02
      相关资源
      最近更新 更多