Home » excel » excel – VBA include argument to subroutine in OnAction

excel – VBA include argument to subroutine in OnAction

Posted by: admin May 14, 2020 Leave a comment

Questions:

I’ve got some code to construct a menu in Excel VBA as follows:

For Each Thing In Array("Foo", "Bar", "Baz")
    With .Controls.Add(Type:=msoControlButton)
         .Caption = "Run with " & Thing
         .FaceId = 2934
         .OnAction = "'" & ThisWorkbook.Name & "'!" & "RunWith" & Thing
    End With
Next Thing

Sub RunWithFoo()
  RunWith "Foo"
End Sub

Sub RunWithBar()
  RunWith "Bar"
End Sub

Sub RunWithBaz()
  RunWith "Baz"
End Sub

Sub RunWith(Thing) ...etc

Is there a way to call RunWith directly without going through the RunWithFoo etc helper methods?

How to&Answers:

Here is an example

Sub Sample()
    Dim Thing
    Thing = "Sid"
    Application.OnKey "^{s}", "'RunWith""" & Thing & """'"
End Sub

Sub RunWith(Thing)
    MsgBox Thing
End Sub