首页 > 解决方案 > VBA插入可以被许多用户使用的TOC

问题描述

我希望设置一个邮件合并(目录合并以使用分页符)模板,然后让用户在创建文件后使用宏生成目录。

我尝试录制一个宏以转到文档中的第一个空格,添加一个分节符,然后插入一个目录并更改编号,使其不包括第一页,但我看到它在加载时使用了我的用户名积木模板。

我意识到它很乱,因为它是记录的,并且我找到了一些更清晰的代码,但是它没有 TOC 的标题。

有没有一种方法可以让任何使用该代码的用户完成这项工作?

Sub Macro1()
'
' Macro1 Macro
'
 Set myTemplate = ActiveDocument.AttachedTemplate
    Selection.HomeKey Unit:=wdStory
    Selection.InsertBreak Type:=wdSectionBreakNextPage
    Selection.HomeKey Unit:=wdStory
    Application.Templates( _
        "C:\Users\myUsername\AppData\Roaming\Microsoft\Document Building Blocks\1033\16\Built-In Building Blocks.dotx" _
        ).BuildingBlockEntries("Automatic Table 1").Insert Where:=Selection.Range _
        , RichText:=True
    If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub

尝试了以下代码,但它仍然使用 mypath ,它必须是当前用户的路径。每个用户的其余路径是否相同?然后也许我可以以某种方式提取当前用户的用户名并将其插入 myUsername。

Sub ToCAndTitle()
With ActiveDocument
  'Insert a Section break before existing content
  .Range(0, 0).InsertBreak Type:=wdSectionBreakNextPage
  .TablesOfContents.Add Range:=.Range(0, 0), RightAlignPageNumbers:=True, _
     UseHeadingStyles:=True, IncludePageNumbers:=True, UseHyperlinks:=True, _
     HidePageNumbersInWeb:=True, UseOutlineLevels:=False
  'Insert a page break before existing content
  .Range(0, 0).InsertBreak Type:=wdPageBreak
  Application.Templates(mypath).BuildingBlockEntries("BuildingBlockName").Insert Where:=.Range(0, 0), RichText:=True
End With
End Sub

标签: vbams-word

解决方案


由于您正在创建分发模板,请将 Building Block 存储在该模板中,而不是存储在您的“私有”构建块模板中。然后,任何使用该模板的人都可以使用它。

  1. 创建要保存为模板中的构建块或从模板创建的文档的内容。选择此内容。
  2. 插入/快速零件/将选择保存到快速零件库
  3. 像往常一样设置名称、画廊和应该存储的类别...
  4. ...从保存中选择将要分发的模板

将问题中的代码更改为:

Sub Macro1()
'
' Macro1 Macro
'
 Set myTemplate = ActiveDocument.AttachedTemplate
    Selection.HomeKey Unit:=wdStory
    Selection.InsertBreak Type:=wdSectionBreakNextPage
    Selection.HomeKey Unit:=wdStory
    myTemplate.BuildingBlockEntries("Automatic Table 1").Insert _
        Where:=Selection.Range _
        , RichText:=True
   'Note: the macro probably does not need the rest of the lines of code
   'that were generated by the macro recorder - comment them out or delete them 
   If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
        ActiveWindow.Panes(2).Close
    End If
    If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
        ActivePane.View.Type = wdOutlineView Then
        ActiveWindow.ActivePane.View.Type = wdPrintView
    End If
    ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
    ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
End Sub

推荐阅读