Word 內建超過 1000 個對話框 (如「字體」、「段落」、「頁面設定」、「列印」等),每個對應一個 WdWordDialog 列舉常數。透過 Application.Dialogs 集合可程式化列舉、呼叫或檢查所有對話框。本文提供完整遍歷代碼與實用技巧。
Sub ListAllWordDialogs()
Dim i As Long
Dim dlgCount As Long
Dim outputDoc As Document
Dim rng As Range
' 建立新文件輸出清單
Set outputDoc = Documents.Add
Set rng = outputDoc.Range
Application.ScreenUpdating = False
' Dialogs 集合索引從 1 開始,上限約 1000+ (視版本)
' 使用錯誤處理避免無效索引中斷
On Error Resume Next
For i = 1 To 2000 ' 足夠大的上限
If Err.Number <> 0 Then
Err.Clear
' 連續多個無效索引可能表示結束,但保守繼續
End If
Dim dlgName As String
dlgName = Application.Dialogs(i).Name ' 取得對話框名稱 (如 "FilePrint")
Dim cmdName As String
cmdName = Application.Dialogs(i).CommandName ' 取得命令名稱 (如 "FilePrint")
If dlgName <> "" Then
rng.InsertAfter "Index: " & i & vbTab & "Name: " & dlgName & vbTab & "Command: " & cmdName & vbCr
End If
Next i
On Error GoTo 0
Application.ScreenUpdating = True
MsgBox "對話框清單已產生於新文件,共 " & outputDoc.Paragraphs.Count & " 項。", vbInformation
End Sub
| 成員 | 型別 | 說明 |
|---|---|---|
Dialogs(index) | Dialog | 傳回指定索引的對話框物件 |
Dialog.Name | String | 對話框顯示名稱 (如 "Font") |
Dialog.CommandName | String | 對應的命令巨集名稱 (如 "FormatFont"),可用 Application.Run cmdName 呼叫 |
Dialog.Show | Long | 顯示對話框:-1 = 使用者按確定,0 = 取消 |
Dialog.Display | Boolean | 設定/取得是否顯示對話框 (False 可無訊息執行預設動作) |
| 索引 (約略) | 常數名稱 | 對話框功能 |
|---|---|---|
| 88 | wdDialogFilePrint | 列印 |
| 174 | wdDialogFileSaveAs | 另存新檔 |
| 150 | wdDialogFormatFont | 字體 |
| 151 | wdDialogFormatParagraph | 段落 |
| 158 | wdDialogFormatBordersAndShading | 邊框和陰影 |
| 331 | wdDialogTableInsertTable | 插入表格 |
| 485 | wdDialogToolsOptions | 選項 |
| 756 | wdDialogInsertSymbol | 插入符號 |
注意:索引號碼在不同 Word 版本間可能不同,請勿在生產代碼中硬編碼索引,應使用
wdDialogXXXX常數名稱。
Application.Dialogs(wdDialogFilePrint).Show。Application.Dialogs(wdDialogFilePrint).Display = False : .Show 直接列印不彈窗。在 VBE 物件瀏覽器 (F2) 搜尋 WdWordDialog 列舉,可見完整常數定義 (約 1000+ 項)。
善用 Dialogs 集合,可實現動態 UI 呼叫、自動化測試、客製化工具列等進階應用。