萬盛學電腦網

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

Word VBA 修改內建命令行為(以 FilePrint 為例記錄列印張數)

Word 允許透過同名巨集「覆寫」內建命令,或用 CommandBarControl.OnAction 指定巨集,來修改/擴充內建命令功能。本文示範兩種寫法並給出實用範例:記錄累計列印份數。

方法一:使用 FindControls 修改 OnAction

Sub Example()
    Dim i As CommandBarControl
    For Each i In Application.CommandBars.FindControls
        If i.ID = 4 Then ' ID=4 相當於 Ctrl+P (檔案/列印)
            i.OnAction = "MySub" ' 指定巨集
        End If
    Next
End Sub

Sub ResetSub()
    Dim i As CommandBarControl
    For Each i In Application.CommandBars.FindControls
        If i.ID = 4 Then
            i.OnAction = "" ' 還原原功能
        End If
    Next
End Sub

Private Sub Document_Close()
    ResetSub
End Sub

Private Sub Document_Open()
    Example
End Sub

方法二:直接建立同名巨集(更簡單)

Sub FilePrint() ' 覆寫「檔案/列印」命令 (Ctrl+P)
    MySub
End Sub

Sub MySub()
    MsgBox "不能使用列印功能!"
End Sub

實用範例:記錄文件累計列印份數(放入自訂樣板)

Sub FilePrint() ' 覆寫 Ctrl+P
    Dim Pc As Integer, Var As Integer
    With Application.Dialogs(wdDialogFilePrint)
        If .Show = -1 Then
            Pc = .NumCopies ' 取得本次列印份數
            Var = Me.Variables("PrintPageCount").Value ' 累計份數
            Me.Variables("PrintPageCount").Value = Pc + Var
            Me.Save ' 儲存文件變數
            MsgBox "目前累計列印份數為 " & Me.Variables("PrintPageCount").Value
        End If
    End With
End Sub

Sub FilePrintDefault() ' 覆寫工具列「列印」按鈕
    ActiveDocument.PrintOut
    Me.Variables("PrintPageCount").Value = Me.Variables("PrintPageCount").Value + 1
    Me.Save
    MsgBox "目前累計列印份數為 " & Me.Variables("PrintPageCount").Value
End Sub

Private Sub Document_Open()
    On Error Resume Next
    Me.Variables.Add Name:="PrintPageCount" ' 初始化文件變數
End Sub

快速取得命令名稱的方法

  • 巨集對話框中的「Word 命令」清單。
  • 巨集對話框執行 ListCommands 列出所有命令。
  • 「自訂」對話框「命令」索引標籤選「所有命令」。
  • 插入域 → MacroButton 域的巨集清單。
  • 最快:Ctrl + Alt + 數字鍵盤 +,游標變「中國結」後點選任意按鈕/命令,彈出的自訂對話框即顯示該命令名稱。

善用此技巧可在不修改核心程式的前提下,為內建命令加入審核、記錄、條件限制等邏輯。

copyright © 萬盛學電腦網 all rights reserved