萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 辦公室軟體 >  >> Word 教學 >> Word 使用技巧

Word VBA 列舉所有內建對話框:Dialogs 集合遍歷代碼範例

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.NameString對話框顯示名稱 (如 "Font")
Dialog.CommandNameString對應的命令巨集名稱 (如 "FormatFont"),可用 Application.Run cmdName 呼叫
Dialog.ShowLong顯示對話框:-1 = 使用者按確定,0 = 取消
Dialog.DisplayBoolean設定/取得是否顯示對話框 (False 可無訊息執行預設動作)

常用對話框索引速查 (部分常用)

索引 (約略)常數名稱對話框功能
88wdDialogFilePrint列印
174wdDialogFileSaveAs另存新檔
150wdDialogFormatFont字體
151wdDialogFormatParagraph段落
158wdDialogFormatBordersAndShading邊框和陰影
331wdDialogTableInsertTable插入表格
485wdDialogToolsOptions選項
756wdDialogInsertSymbol插入符號

注意:索引號碼在不同 Word 版本間可能不同,請勿在生產代碼中硬編碼索引,應使用 wdDialogXXXX 常數名稱。

實用應用場景

  1. 動態呼叫對話框:讀取設定檔中的對話框名稱 → Application.Dialogs(wdDialogFilePrint).Show。
  2. 建立自訂功能區按鈕:遍歷 Dialogs 產生下拉選單,使用者挑選對話框加入自訂索引標籤。
  3. 無訊息執行預設動作:Application.Dialogs(wdDialogFilePrint).Display = False : .Show 直接列印不彈窗。
  4. 教學/文件產生:自動產生所有對話框索引對照表供查閱。

取得官方常數清單

在 VBE 物件瀏覽器 (F2) 搜尋 WdWordDialog 列舉,可見完整常數定義 (約 1000+ 項)。

善用 Dialogs 集合,可實現動態 UI 呼叫、自動化測試、客製化工具列等進階應用。

copyright © 萬盛學電腦網 all rights reserved