使用CallByName调用classModule中的函数很容易.标准模块中的函数怎么样?
''#inside class module
''#classModule name: clsExample
Function classFunc1()
MsgBox "I'm class module 1"
End Function
''#
''#inside standard module
''#Module name: module1
Function Func1()
MsgBox "I'm standard module 1"
End Function
''#
''# The main sub
Sub Main()
''# to call function inside class module
dim clsObj as New clsExample
Call CallByName(clsObj,"ClassFunc1")
''# here's the question... how to call a function inside a standard module
''# how to declare the object "stdObj" in reference to module1?
Call CallByName(stdObj,"Func1") ''# is this correct?
End Sub
Run Code Online (Sandbox Code Playgroud)
我认为 jtolle 的回答最好地解决了这个问题 - 对 Application.Run 的小引用可能就是答案。提问者不想简单地使用 func1 或 Module1.func1 - 首先想要使用 CallByName 的原因是所需的 function.sub 名称在编译时未知。在这种情况下,Application.Run 确实有效,例如:
Dim ModuleName As String
Dim FuncName As String
Module1Name = "Module1"
FuncName = "func1"
Application.Run ModuleName & "." & FuncName
Run Code Online (Sandbox Code Playgroud)
您还可以在模块名称之前添加项目名称,并添加另一个句点“.”。不幸的是,Application.Run 不返回任何值,因此虽然您可以调用函数,但您不会获得其返回值。
CallByName 仅适用于类对象。
如果您的子例程位于标准模块中,您可以这样做:
Sub Main()
Module1.Func1
End Sub
Run Code Online (Sandbox Code Playgroud)
如果它是一个函数,那么您可能想要捕获返回值;像这样的东西:
Sub Main()
Dim var
var = Module1.Func1
End Sub
Run Code Online (Sandbox Code Playgroud)