Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a sub or a function exist

Is there any way to check if a sub or a function exist?

sub mySub()
 'some code
end sub

something like if exist(mySub)

like image 741
Vixed Avatar asked Mar 10 '16 14:03

Vixed


People also ask

How do you check if a function exists or not?

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.

How do you define a sub or a function in VBA?

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.

What is Sub or function not defined?

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.

What is sub in VBA code?

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.


1 Answers

Update:

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.

like image 88
user692942 Avatar answered Sep 27 '22 18:09

user692942