应在Microsoft Word 2007 Macro中使用哪些VBA代码来创建目录

时间:2013-02-28 21:34:49

标签: vba word-vba tableofcontents

我想在Microsoft Word 2007中定义一个宏,当按下热键时,该宏会使用提供的自动样式插入目录。我成功定义了一个宏来插入非样式(例如基本)的目录,如下所示:

Sub InsertTableOfContents()
'
' InsertTableOfContents Macro
'
'
    With ActiveDocument
        .TablesOfContents.Add Range:=Selection.Range, RightAlignPageNumbers:= _
            True, UseHeadingStyles:=True, UpperHeadingLevel:=1, _
            LowerHeadingLevel:=3, IncludePageNumbers:=True, AddedStyles:="", _
            UseHyperlinks:=True, HidePageNumbersInWeb:=True, UseOutlineLevels:= _
            True
        .TablesOfContents(1).TabLeader = wdTabLeaderDots
        .TablesOfContents.Format = wdIndexIndent
    End With
End Sub

但是,当我尝试按如下方式插入样式目录时:

Sub InsertStyledTOC()
'
' Macro to insert a table of contents styled like Automatic Table 2
'
ActiveDocument.AttachedTemplate.BuildingBlockEntries("Automatic Table 2"). _
    Insert Where:=Selection.Range, RichText:=True
End Sub

我收到以下错误:

  

运行时错误5941集合中请求的成员不存在

我相信这表明BuildingBlockEntries的引用成员(例如自动表2)不存在,但我不清楚为什么或如何纠正它。

感谢您的帮助

编辑 - 我尝试按照建议将文件路径用于应用程序的默认Building Blocks模板:

Application.Templates("C:\Program Files\Microsoft Office\Office12\Document Parts\1033\Building Blocks.dotx").BuildingBlockEntries("Automatic Table 2").Insert Where:=Selection.Range _ , RichText:=True

但是,我仍然收到错误:Run-time error 5941 The requested member of the collection does not exist

1 个答案:

答案 0 :(得分:1)

您的代码需要在附加的模板中找到构建块,如果您没有做任何特殊的事情,可能是Normal.dotm。 Microsoft实际上将内置构建块存储在不同的模板中。如果您录制宏,您将看到此模板所在的位置(我的位于“C:\ Users \ owner \ AppData \ Roaming \ Microsoft \ Document Building Blocks \ 1033 \ 14 \ Built-In Building Buildings.dotx”)

所以,你有两个选择。您可以使用Templates集合到达该模板并从那里插入构建块(宏录制器是您的朋友)。或者,您可以将构建块保存到Normal.dotm,以便更轻松地访问它。为此,请单击“插入”>快速文字> Buliding Blocks,在列表中找到您的Building Block,编辑其属性,并将其保存为Normal。如果你这样做,你的代码应该有效(我有2010年,但我认为这非常相似)。

我不知道这两个选项之间有什么真正的区别,假设这只是为了你而不是你需要分发的东西。

编辑添加我从宏录制器获取的代码:

    Application.Templates( _
    "C:\Users\owner\AppData\Roaming\Microsoft\Document Building Blocks\1033\14\Built-In Building Blocks.dotx" _
    ).BuildingBlockEntries("Automatic Table 2").Insert Where:=Selection.Range _
    , RichText:=True

因此,您应该尝试使用它替换InsertStyledTOC中的代码。