2013-02-28 69 views
2

我想在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

+0

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

+0

另外,你是否嘗試過錄制自己的宏,插入所需樣式的TOC並檢查代碼? – mkingston 2013-02-28 22:12:16

+0

上面的代碼是作爲記錄的宏的結果生成的,其中我從References-> Table of Contents菜單中選擇了目錄(Automatic Table 2)。我還沒有嘗試輸入調試代碼,所以我會試一試。對不起,對vba和宏有新意。 – Christian 2013-03-01 13:28:08

回答

1

您的代碼需要在附加模板中找到Building Blocks,如果您沒有做了什麼特別的,大概是Normal.dotm。微軟實際上將內置的構建塊存儲在不同的模板中。如果您錄製一個宏,您將看到該模板所在的位置(我的位置是「C:\ Users \ owner \ AppData \ Roaming \ Microsoft \ Document Building Blocks \ 1033 \ 14 \ Built-In Building Blocks.dotx」) 。

所以,你有兩個選擇。您可以使用Templates集合來訪問該模板並從那裏插入構建塊(宏記錄器是您的朋友)。或者,您可以將構建塊保存到Normal.dotm以使訪問更容易一些。爲此,請單擊插入>快速文本>建立塊,在列表中找到您的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代碼。

+0

謝謝你的幫助。宏中記錄的功能需要生成的vba代碼來指定內置構建塊的位置? – Christian 2013-03-01 13:39:52

+0

其實,我已經找到了'Building Blocks'的位置,但我不確定如何使用模板集合來訪問它,你能提供一個例子嗎? – Christian 2013-03-01 13:54:40

+0

將代碼添加到答案中。 – Christina 2013-03-01 19:19:47