在使用 VBA 自動化處理 Word 文件時,Documents 集合與 Document 物件是核心操作對象。熟悉其常用屬性,能讓您快速取得文件資訊、控制內容結構、管理版面設定等。本文整理實務上最常用的屬性,並以分類說明方式呈現,方便開發者查閱與應用。
| 屬性 | 說明 |
|---|---|
| Bookmarks.Count | 書籤總數 |
| Comments.Count | 批註總數 |
| Fields.Count | 欄位總數 |
| Footnotes.Count | 腳註總數 |
| Endnotes.Count | 尾註總數 |
| Hyperlinks.Count | 超連結總數 |
| Shapes.Count | 繪圖物件總數 |
| Tables.Count | 表格總數 |
| Styles.Count | 樣式總數 |
| ListParagraphs.Count | 清單段落總數 |
| ListTemplates.Count | 清單樣板總數 |
| Indexes.Count | 索引總數 |
| TablesOfContents.Count | 目錄總數 |
| TablesOfFigures.Count | 圖表目錄總數 |
| TablesOfAuthorities.Count | 引文目錄總數 |
| TablesOfAuthoritiesCategories.Count | 引文目錄分類總數 |
透過 Paragraphs(index) 可存取個別段落的格式屬性:
' 列印目前文件所有段落文字與樣式
For Each para In ActiveDocument.Paragraphs
Debug.Print para.Range.Text, para.Range.Style.NameLocal
Next
' 設定文件開啟密碼
ActiveDocument.Password = "MySecret123"
' 判斷文件是否已儲存
If Not ActiveDocument.Saved Then
ActiveDocument.Save
End If
Application.ScreenUpdating = False 提升效能。ActiveDocument 前,確認 Documents.Count > 0 避免錯誤。PageSetup 或段落格式物件。掌握這些屬性,即能在 VBA 中靈活掌控 Word 文件結構與內容,大幅提升自動化開發效率。