Is there any way to check if a sub or a function exist?
sub mySub()
'some code
end sub
something like if exist(mySub)
To prevent the error, you can first check if a function exists in your current JavaScript environment by using a combination of an if statement and the typeof operator on the function you want to call.
When writing the sub, we use the “Sub” keyword and a name as the procedure name to declare the sub. The sub procedure should be followed by the task to be performed, written in VBA language. The sub should close with the statement End Sub.
A Sub or Function must be defined in order to be called. Possible causes of this error include: Misspelling the procedure name. Trying to call a procedure from another project without explicitly adding a reference to that project in the References dialog box.
A Sub procedure is a series of Visual Basic statements enclosed by the Sub and End Sub statements that performs actions but doesn't return a value. A Sub procedure can take arguments, such as constants, variables, or expressions that are passed by a calling procedure.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With