Reputation: 3509
Is there any way to check if a sub or a function exist?
sub mySub()
'some code
end sub
something like if exist(mySub)
Upvotes: 9
Views: 5869
Reputation: 16682
So I knew there was a better method for doing this and it's 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
There is nothing built into VBScript to do this but you can build something using 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
Drawback with this approach is it actually runs the procedure if it exists.
Upvotes: 17