9

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

sub mySub()
 'some code
end sub

something like if exist(mySub)

1
  • If this is because you are linking multiple source files, you can add a const x = true to each then check for x later on Commented Mar 10, 2016 at 15:05

1 Answer 1

16

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Why ExecuteGlobal? I'm using your function using just Execute and works like a charm!
@Vixed ExecuteGlobal executes in the global scope where as Execute is scope dependent, it will work for simple commands but more complex ones I find ExecuteGlobal works better.
@Vixed There is a cleaner way of doing this and that is to use GetRef() I knew one existed (used it before) just couldn't remember the command. See updated answer.
I've built this function Function runIfExists(procName) On Error Resume Next Execute ("Call "&procName) End Function But I get the an error Error 'ASP 0115', Trappable error (C0000005) Do you have any tips for me?!
@Vixed Nothing springs to mind, may be best asking another question and added the function you've built. In the mean-time maybe this will help, Classic ASP : C0000005 Error on execution. I actually thought you had tested it and it worked, did you follow the code in the above answer, anything different? How you calling it for example?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.