我想在Microsoft Word 2007中定義一個宏,當按下熱鍵時插入一個帶有提供的自動樣式的內容列表。我成功地定義的宏來插入的內容的非風格(例如基本)表如下:在Microsoft Word 2007宏中應該使用哪些VBA代碼來創建目錄
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
我得到以下錯誤:
Run-time error 5941 The requested member of the collection does not exist
我beleive這表明,所引用的成員BuildingBlockEntries
(如自動錶2)不存在,但我不清楚爲什麼或如何糾正它。
感謝您的幫助
編輯 - 我試圖使用文件路徑到應用程序的默認構建基塊模板的建議:
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
TOC'Selection.Range'?那麼你只是試圖將一個樣式應用於'Selection.Range'?你知道'BuildingBlockEntries'是什麼嗎? (我不知道!)。嘗試在您的即時窗口中輸入(從VBA編輯器中按Ctrl + G):'for i = 1 to activedocument.AttachedTemplate.buildingblockentries.count:debug.Print activedocument.AttachedTemplate.buildingblockentries(i).name:next i' – mkingston 2013-02-28 22:08:53
另外,你是否嘗試過錄制自己的宏,插入所需樣式的TOC並檢查代碼? – mkingston 2013-02-28 22:12:16
上面的代碼是作爲記錄的宏的結果生成的,其中我從References-> Table of Contents菜單中選擇了目錄(Automatic Table 2)。我還沒有嘗試輸入調試代碼,所以我會試一試。對不起,對vba和宏有新意。 – Christian 2013-03-01 13:28:08