Check if a sub-function or function exists

Is there a way to check if a sub or function exists?

sub mySub() 'some code end sub 

something like if exist(mySub)

+5
source share
1 answer

Update:

So, I knew there was a better way for this, and using 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 

Output

  Test Doesn't Exist
 Hello exists

Nothing is built into VBScript, but you can build something with On Error Resume Next and ExecuteGlobal() .

 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 

Output

  Test Doesn't Exist
 Hello ran
 Test Doesn't Exist

The disadvantage of this approach is the execution of the procedure, if it exists.

+7
source

Source: https://habr.com/ru/post/1244825/


All Articles