Dynamically call a macro passing parameters from shape OnAction property

后端 未结 2 1882
[愿得一人]
[愿得一人] 2020-12-20 19:20

Well, my problem is that I have created a VBA Sub that receives an excel Cell reference and 2 text values and a Variant as parameter.

Sub CreateButton(oCell,         


        
相关标签:
2条回答
  • 2020-12-20 19:33

    You can assign a string to OnAction that has the sub to call followed by its arguments (note the whole string wrapped in single quotes)

    Like:

    Shape.OnAction = "'SubToCallOnAction ""Hello World!""'"
    
    Sub SubToCallOnAction(text As String)
    
        MsgBox text
    
    End Sub
    

    Numeric arguments don't need the quotes (though they will be passed in via Number -> default string conversion -> default number conversion)

    So, I guess, what you are wanting to do is pass in the name of the button that was clicked:

    Shape.OnAction = "'SubToCallOnAction """ & Shape.Name & """'"
    

    More advanced and flexible usage could be something like:

    'Set the button up like:
    databaseTable = "tbl_ValidAreas"
    databaseField = "Country"
    Shape.OnAction = _
        "'SubToCallOnAction """ & _
        Shape.Name & """ """ & _
        databaseTable & """ """ & 
        databaseField & """'"
    
    ...
    Sub SubToCallOnAction(buttonID As String, ParamArray args)
    
        Select Case buttonID
            Case "button1"
                'get the relevant data or whatever using the ParamArray args
                Call GetData(args(0),args(1))
            ...
        End Select
    
    End Sub
    
    0 讨论(0)
  • 2020-12-20 19:40

    -- For people who find this page in 2016+ --

    Cor_Blimey's solution doesn't work in Excel 2003. You have to add commas instead of blanks between the arguments, like so:

    Shape.OnAction = _
        "'SubToCallOnAction """ & _
        Shape.Name & """,""" & _
        databaseTable & """,""" & 
        databaseField & """'
    
    0 讨论(0)
提交回复
热议问题