我很好奇是否有办法动态调用函数。例如。
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
不是一件紧迫的事......只是好奇。任何其他创造性的事情要做功能调用也是受欢迎的。
谢谢!
EDIT1: 这是我的代码和下面列出的错误:
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'无法运行宏'foo1'。宏可能在此工作簿中不可用,或者可能禁用所有宏。
答案 0 :(得分:16)
你想要run method!
Sub callSomeFoo(i as Integer)
Application.Run "foo" & i
End Sub
但那不起作用,VBA不喜欢名字foo1
,所以它不起作用。
这是因为FOO1也可以是细胞参考。第一个arg Application.Run可以是一个Range对象,因此它会评估FOO1 它是一个单元格,因为那个单元格是空的,不知道该怎么做。 - 迪克库斯莱卡
通过选择更长的更好的方法名称可以很容易地解决这个问题。
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