在 VBA 中使用变量作为函数名和参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4510744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 12:27:10  来源:igfitidea点击:

Using variables as function names and parameters in VBA

ms-accessvbaaccess-vba

提问by Jay

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.

我的 VBA 逻辑 sFunctionName、sParam1、sParam2、sParam3 中有以下变量,所有字符串变量都是从表中填充的。我想使用这些变量来调用函数。我试过使用 Application.Run(sFunctionName, sParam1) 并且语句失败,但是当我使用 Application.Run(sFunctionName) 时它工作得很好。我也尝试过 Eval 对某人的建议没有运气。有人可以让我知道我错过了什么,或者我是否可以做我正在尝试做的事情?我感谢任何和所有的帮助。

Thanks, J

谢谢,J

回答by PowerUser

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

#1. 关于Eval(): Per Access 的帮助文件,

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

您可以使用 Eval 函数计算结果为文本字符串或数值的表达式。

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

因此,如果您的函数解析为文本或数字,那么您就可以开始了。
IEDebug.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?

#2. 我认为您的Run()问题不在于实际函数本身,而在于您如何应用它。我拼凑了一些快速代码。这有帮助吗?

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 xin the Immediate Window will give you a 2)

debug.print x在立即窗口中调用它会给你一个 2)

回答by Marek

Try running a method without braces, like:

尝试运行不带大括号的方法,例如:

Application.Run sFunctionName, sParam1