Excel VBA中的dynamic函数调用

我只是好奇,如果有可能dynamic调用函数的方式。 例如。

Sub foo1() Debug.Print "in foo1" End Sub Sub foo2() Debug.Print "in foo2" End Sub 

有没有办法可以做到这样的事情:

 Sub callSomeFoo(i as Integer) Call foo&i End Sub 

或者是这样的必要的东西:

 Sub callSomeFoo(i as Integer) Select Case i Case 1 Call foo1 Case Else Call foo2 End Select End Sub 

没有紧迫的事情…只是好奇。 任何其他有创意的事情都可以做function调用。

谢谢!

编辑1:这是我有的代码和下面列出的错误:

 Sub foo1() Debug.Print "in foo1" End Sub Sub foo2() Debug.Print "in foo2" End Sub Sub callSomeFoo() Dim i% 'using a cell on the worksheet to determine the function. Happens to be "1" i = Sheets("Sheet1").Range("A1").Value 'Line below works Call foo1 'Line below gives me an error Application.Run "foo"&i End Sub 

错误是:

运行时错误“1004”无法运行macros'foo1'。 macros可能不在此工作簿中可用或所有macros可能被禁用。

你想要的运行方法 !

 Sub callSomeFoo(i as Integer) Application.Run "foo" & i End Sub 

但是,这不会工作,VBA不喜欢名称foo1 ,所以它不会工作。

这是因为FOO1也可能是一个单元格引用。 Application.Run的第一个参数可以是一个Range对象,所以它评估FOO1,认为它是一个单元格,并且由于该单元格是空的,不知道该怎么做。 – 迪克Kusleika

这可以通过select更长的更好的方法名称来解决。

经过testing的工作例子

 Option Explicit Public Sub TestDynamic1() Debug.Print "TestDynamic 1" End Sub Sub TestDynamic2() Debug.Print "TestDynamic 2" End Sub Private Sub TestDynamic3() Debug.Print "TestDynamic 3" End Sub Sub callTestDynamic(i As Integer) On Error GoTo DynamicCallError Application.Run "TestDynamic" & i Exit Sub DynamicCallError: Debug.Print "Failed dynamic call: " & Err.Description End Sub Public Sub TestMe() callTestDynamic 1 callTestDynamic 2 callTestDynamic 3 callTestDynamic 4 End Sub