昱得資訊工作室
麻辣學園
歡迎光臨, 訪客. 請先 登入註冊一個帳號.
您忘了 啟用您的帳號嗎?
2008-07-25, 03:15:56
首頁 說明 登入 註冊 贊助論壇 想當作者?
新聞: 請會員來訪時務必完成登入,為維護論壇品質,將不定期刪除長時間未登入的會員!!


+  麻辣家族討論區
|-+  MS Office 系列
| |-+  WORD (版主: leonchou)
| | |-+  [VBA] 自訂CommandBarButton事件 (插入自動圖文集)
0 會員 以及 1 訪客 正在閱讀本篇主題. « 上一篇主題 下一篇主題 »
頁: [1] 向下 列印
作者 主題: [VBA] 自訂CommandBarButton事件 (插入自動圖文集)  (閱讀 1991 次)
leonchou
版主
*
離線 離線

文章: 1160


[VBA] 自訂CommandBarButton事件 (插入自動圖文集)
« 於: 2005-05-28, 02:49:09 »

這次的需求是自訂一個下拉式功能表,加入數個按鈕;
按鈕的動作是在文件中插入以按鈕名稱為名的自動圖文集項目。
由於 CommandBarButton的 OnAtion 不接受帶參數的巨集,
又不想重複寫多個類似的巨集,所以有以下的解決方案。

其實在建立CommandBarButton時直接指定爲自動圖文集項目是可行的,
但如果你真的不想那樣做,那麼以下介紹
自訂 CommandBarButton 的 Click 事件:

1. 新增一個物件類別模組 (使用預設名稱Class1),包含以下代碼 --
Public WithEvents cmdBarButton As Office.CommandBarButton

Private Sub cmdBarButton_Click(ByVal Ctrl As Office.CommandBarButton, _
  CancelDefault As Boolean)
  InsertAutoText Ctrl.Caption
  CancelDefault = True
End Sub

2. 建立下拉式功能表巨集所在模組的程式碼 --
Dim btnClass() As New Class1

Public Sub CreateCommandBarPopup()

  Dim objCommandBarControl As Office.CommandBarControl
  Dim objCommandBarButton As Office.CommandBarButton
  
  '刪除原有的下拉式功能表控制項
  For Each objCommandBarControl In CommandBars("Standard").Controls
    If objCommandBarControl.Caption = "我的功能表\" Then
      objCommandBarControl.Delete
    End If
  Next objCommandBarControl
  
  '在"一般"工具列建立下拉式功能表及按鈕
  With CommandBars("Standard").Controls.Add(msoControlPopup)
    .Caption = "我的功能表\\"
    myCount = 0
    For Each itm In Array("審計單位", "建設單位")
      Set objCommandBarButton = .Controls.Add(msoControlButton)
      With objCommandBarButton
        .Caption = itm
        .Tag = .Caption
      End With
      myCount = myCount + 1
      ReDim Preserve btnClass(1 To myCount)
      '將CommandBarButton逐一連結到上面自定義的cmdBarButton物件
      Set btnClass(myCount).cmdBarButton = objCommandBarButton
    Next itm

  End With

End Sub

Sub InsertAutoText(strAutoText As String)
' 在目前位置插入自動圖文集
  ActiveDocument.AttachedTemplate.AutoTextEntries(strAutoText).Insert Where:=Selection.Range
End Sub

如此當按下自定義功能表的按鈕就會觸發物件類別模組Class1 的cmdBarButton_Click 事件,自動判別其 Caption 屬性並呼叫 InsertAutoText 程式。

PS.
1. 相關的自動圖文集項目必須已存在,若沒有請先建立。
2. 在文件中插入自動圖文集的代碼也可以直接寫在類模組 Class1 的 cmdBarButton_Click 事件之中。

相關參考: UserForm - 自訂1個代表所有按鈕的Click事件
已記錄

頁: [1] 向上 列印 
« 上一篇主題 下一篇主題 »
跳到:  


本頁花了 0.435 秒, 以及 19 次的資料庫查詢.