Jay
Jay

Reputation: 11

Using variables as function names and parameters in VBA

I have the following variables in my VBA logic sFunctionName, sParam1, sParam2, sParam3 all string variables populated from a table. I would like to use those variables to call a function. I have tried using Application.Run(sFunctionName, sParam1) and the statement fails, However when i use Application.Run(sFunctionName) it works just fine. I have also tried Eval on someones suggestion with no luck. Can someone let me know what I am missing, or if i can even do what I am attempting to do? I appreciate any and all help.

Thanks, J

Upvotes: 1

Views: 10948

Answers (2)

Marek
Marek

Reputation: 707

Try running a method without braces, like:

Application.Run sFunctionName, sParam1

Upvotes: 1

PowerUser
PowerUser

Reputation: 11801

#1. Regarding Eval(): Per Access's help files,

You can use the Eval function to evaluate an expression that results in a text string or a numeric value.

So, if your function resolves to text or numeric, then you're good to go.
i.e. Debug.Print Eval("Date()")

#2. I don't think your problem with Run() is with the actual function itself, but rather how you are applying it. I threw together some quick code. Does this help?

Function AddOne(What As Integer) As Integer
    AddOne = What + 1
End Function

Function x()
    Dim WhichFunc As String
    WhichFunc = "AddOne"
    Dim What As Integer
    What = 1
    x = Run(WhichFunc, What)
End Function

(Calling this with debug.print x in the Immediate Window will give you a 2)

Upvotes: 2

Related Questions