Prenesite argumente makrom iz gumbov in menijev z uporabo VBA v programu Microsoft Excel

Anonim

Spodnji primer prikazuje, kako lahko ustvarite gumbe/menije CommandBar, ki posredujejo enega ali več argumentov v makro.
primer prikazuje tudi, kako lahko v bližnjični meni Celica dodate nov element.

Sub AddCommandToCellShortcutMenu () Dim i As Integer, ctrl As CommandBarButton DeleteAllCustomControls "izbrišite kontrolnike, če že obstajajo", ustvarite nove kontrolnike z Application.CommandBars (25) "meni bližnjice v celici" dodajte navaden gumb ukazne vrstice Set ctrl = .Controls.Add (msoControlButton,,,, True) S ctrl .BeginGroup = True .Caption = "Nov meni1". FaceId = 71 .State = msoButtonUp .Style = msoButtonIconAndCaption .Tag = "TESTTAG1" .OnAction = "MyMacroNa ' gumb, ki posreduje en argument niza Nastavi ctrl = .Controls.Add (msoControlButton,,,, True) s ctrl .BeginGroup = False .Caption = "Nov meni2". FaceId = 72 .Style = msoButtonIconAndCaption .Tag = "TESTTAG2" .OnAction = "'MyMacroName2" "New Menu2" "'" End With "doda gumb, ki posreduje en argument niza Set ctrl = .Controls.Add (msoControlButton,,,, True) z ctrl .BeginGroup = False .Caption =" Novo Meni 3 ". FaceId = 73. Stil = msoButtonIconAndCaption .Tag =" TESTTAG3 ".OnAction = "'MyMacroName2" "" & .Caption & "" "" "End With" dodajte gumb, ki posreduje dva argumenta, niz in celo število. Nastavi ctrl = .Controls.Add (msoControlButton,,,, True) s ctrl. BeginGroup = False .Caption = "Nov meni4". FaceId = 74. Stil = msoButtonIconAndCaption .Tag = "TESTTAG4" .OnAction = "'MyMacroName3" "" &. = Nič Končaj Sub Sub DeleteAllCustomControls () 'izbriši kontrolnike, če že obstajajo Dim i As Integer For i = 1 To 4 DeleteCustomCommandBarControl "TESTTAG" & i Next i End Sub Private Sub DeleteCustomCommandBarControl (CustomControlTag As String)' izbriše vse kontrolnike CommandBar z Tag = CustomControlTag On Error Nadaljuj Naslednje Naredite Application.CommandBars.FindControl (,, CustomControlTag, False). Izbriši zanko do Application.CommandBars.FindControl (,, _ CustomControlTag, False) Ni ničesar pri napaki GoTo 0 End Sub 'makro uporablja gumbi ukazne vrstice Sub MyMacroName1 () MsgBox "The time is" & Format (Time, "h h: mm: ss ") End Sub Sub MyMacroName2 (Izbirno MsgBoxCaption As String =" UNKNOWN ") MsgBox" The time is "& Format (Time," hh: mm: ss "),, _" Ta makro je bil zagnan od " & MsgBoxCaption End Sub Sub MyMacroName3 (MsgBoxCaption As String, DisplayValue As Integer) MsgBox "The time is" & Format (Time, "hh: mm: ss"),, _ MsgBoxCaption & "" & DisplayValue End Sub