检查子程序或函数是否存在

Check if a sub or a function exist

有什么方法可以检查子程序或函数是否存在?

sub mySub()
 'some code
end sub

类似于if exist(mySub)

更新:

所以我知道有更好的方法可以做到这一点,它使用 GetRef()

Function Exist(procName)
    On Error Resume Next
    Dim proc: Set proc = GetRef(procName)
    Exist = (Not proc Is Nothing)
End Function

Function Hello()
    WScript.Echo "Hello Ran"
End Function

If Exist("test") Then  'Returns False (0)
    WScript.Echo "Test Exists"
Else
    WScript.Echo "Test Doesn't Exist"
End If

If Exist("Hello") Then  'Returns True (-1)
    WScript.Echo "Hello Exists"
Else
    WScript.Echo "Hello Doesn't Exist"
End If

输出

Test Doesn't Exist
Hello Exists

VBScript 中没有内置任何东西来执行此操作,但您可以使用 On Error Resume NextExecuteGlobal().

构建一些东西
Function Exist(procName)
    On Error Resume Next
    ExecuteGlobal "Call " & procName & "()"
    Exists = (Err.Number = 0)
End Function

Function Hello()
    WScript.Echo "Hello Ran"
End Function

If Exist("test") Then  'Returns False (0)
    WScript.Echo "Test Exists"
Else
    WScript.Echo "Test Doesn't Exist"
End If

If Exist("hello") Then  'Returns True (-1)
    WScript.Echo "Test Exists"
Else
    WScript.Echo "Test Doesn't Exist"
End If

输出

Test Doesn't Exist
Hello Ran
Test Doesn't Exist

这种方法的缺点是它实际上会运行该过程(如果存在)。