BWG*_*BWG 11 excel vba excel-vba
我正在尝试使用基于组合框值在运行时生成的变量名称调用函数.这在大多数语言中都很简单,但我似乎无法在Excel VBA中弄明白,我怀疑这是因为我并不真正理解编译器的工作原理.我发现有几个帖子很接近,但似乎并没有这么做.下面的代码是错误的,但应该知道我想要什么.
谢谢
Sub main()
'run formatting macros for each institution on format button click
Dim fn As String
Dim x As Boolean
'create format function name from CB value
fn = "format_" & CBinst.Value
'run function that returns bool
x = Eval(fn)
...
End Sub
Run Code Online (Sandbox Code Playgroud)
sha*_*esh 18
CallByName 是你完成任务所需要的.
示例:Sheet1中的代码
Option Explicit
Public Function Sum(ByVal x As Integer, ByVal y As Integer) As Long
Sum = x + y
End Function
Run Code Online (Sandbox Code Playgroud)
代码是Module1(bas模块)
Option Explicit
Sub testSum()
Dim methodToCall As String
methodToCall = "Sum"
MsgBox CallByName(Sheet1, methodToCall, VbMethod, 1, 2)
End Sub
Run Code Online (Sandbox Code Playgroud)
运行该方法使用字符串变量中给出的方法名称testSum调用该方法Sum,传递2个参数(1和2).函数调用的返回值作为输出返回 CallByName.