Home > Software engineering >  VBA running a function by name of string
VBA running a function by name of string

Time:12-23

is it possible to run a function bases on a variable from a cell in excel?

Option Explicit

Dim retval As Integer

Sub main()
    
    Dim sht As Worksheet
    Set sht = ActiveSheet
    
    Dim usedFun As String
    'get function name from cell
    usedFun = Range("C3").Value
    
    Dim firNum As Integer
    Dim secNum As Integer
    firNum = 3
    secNum = 1
 
    'run named function
    Run usedFun(firNum, secNum)
    
    Debug.Print retval
    
End Sub

Public Function plus(firNum As Integer, secNum As Integer)
    retval = firNum   secNum
End Function

Public Function minus(firNum As Integer, secNum As Integer)
    retval = firNum - secNum
End Function


i get "compile error, expected array" can do it with case select, but the many cases ends up in clumsy looking code any other suggestions?

CodePudding user response:

You were very close - it would be:

Run usedFun, firNum, secNum
  • Related