用VBA代碼處理菜單和工具欄之一

字號(hào):

獲取菜單和工具欄的信息
    在所有的OFFICE組件應(yīng)用程序中都包含有內(nèi)置的工具欄,并且可以進(jìn)行進(jìn)一步的自定義顯示相關(guān)命令,它們一共有三種類型:菜單欄,工具欄和彈出式菜單欄(本主題以工具欄代表三種類型來(lái)描述)。
    你可以用下面的一段程序在立即窗口中顯示它們的所有的工具欄以及工具欄上所包含的命令控件:
    Function CBPrintCBarInfo(strCBarName As String) As Variant
     ' This procedure prints (to the Debug window) information
     ' about the command bar specified in the strCBarName argument
     ' and information about each control on that command bar.
     Dim cbrBar As CommandBar
     Dim ctlCBarControl As CommandBarControl
     Const ERR_INVALID_CMDBARNAME As Long = 5
     On Error GoTo CBPrintCBarInfo_Err
     Set cbrBar = Application.CommandBars(strCBarName)
     Debug.Print "CommandBar: " & cbrBar.Name & vbTab & "(" _
     & CBGetCBType(cbrBar) & ")" & vbTab & "(" _
     & IIf(cbrBar.BuiltIn, "Built-in", "Custom") & ")"
     For Each ctlCBarControl In cbrBar.Controls
     Debug.Print vbTab & ctlCBarControl.Caption & vbTab & "(" _
     & CBGetCBCtlType(ctlCBarControl) & ")"
     Next ctlCBarControl
    CBPrintCBarInfo_End:
     Exit Function
    CBPrintCBarInfo_Err:
     Select Case Err.Number
     Case ERR_INVALID_CMDBARNAME
     CBPrintCBarInfo = "'" & strCBarName & _
     "' is not a valid command bar name!"
     Case Else
     CBPrintCBarInfo = "Error: " & Err.Number _
     & " - " & Err.Description
     End Select
     Resume CBPrintCBarInfo_End
    End Function
    你可以在access的Visual Basic編輯器中的立即窗口中運(yùn)行這個(gè)函數(shù)得到access所有的菜單或工具欄的命令按鈕,例如,可以在立即窗口中鍵入以下命令:
     CBPrintCBarInfo(“Web”)
    回車后你能在立即窗口中顯示出Web工具欄所包含的所有命令集合,如下圖:
    如果命令按鈕的類型顯示為“Popup”時(shí), 例如“收藏夾”這個(gè)命令它本身就是一個(gè)彈出式工具欄,你同樣可以用本函數(shù)來(lái)得到它個(gè)每一個(gè)命令按鈕的清單,如:
     CBPrintCBarInfo(“favorites”)
    你可以用名稱或集合索引來(lái)訪問(wèn)工具欄集合的每個(gè)工具欄,注意與其它集合不同的是所有集合索引都是從1開(kāi)始的。