Excel VBA call function with variable name

后端 未结 4 1149
不思量自难忘°
不思量自难忘° 2020-12-28 10:34

I\'m trying to call a function with a variable name that is generated at run time based upon a combo box value. This is straightforward in most languages but I can\'t seem

4条回答
  •  佛祖请我去吃肉
    2020-12-28 10:48

    CallByName is what you'll need to accomplish the task.

    example: Code in Sheet1

    Option Explicit
    Public Function Sum(ByVal x As Integer, ByVal y As Integer) As Long
        Sum = x + y
    End Function
    

    Code is Module1 (bas module)

    Option Explicit
    
    Sub testSum()
    Dim methodToCall As String
    methodToCall = "Sum"
    
    MsgBox CallByName(Sheet1, methodToCall, VbMethod, 1, 2)
    End Sub
    

    Running the method testSum calls the method Sum using the name of the method given in a string variable, passing 2 parameters (1 and 2). The return value of the call to function is returned as output of CallByName.

提交回复
热议问题