Is there any way to check to see if a VBScript function is defined?
Asked Answered
S

3

15

This is probably just wishful thinking...

Is there any way to check to see if an ASP/VBScript function is defined before calling it?

Sweatband answered 28/5, 2009 at 15:10 Comment(0)
J
16

Here is my solution which works on the same principle, but the hacky-ness is pretty self-contained:

Function FunctionExists( func_name )
    FunctionExists = False 

    On Error Resume Next

    Dim f : Set f = GetRef(func_name)

    If Err.number = 0 Then
        FunctionExists = True
    End If  
    On Error GoTo 0

End Function 
Joinder answered 11/9, 2009 at 22:43 Comment(4)
Yeah - that's what I ended up doing with it. :-)Sweatband
You could simplify this to FunctionExists = (Err.Number = 0) to set the Boolean.Hose
@Lankymart, doesn't work the same. Not sure why not.Steepen
Can simplify to: If Err.number = 0 Then FunctionExists = TrueSteepen
S
6

It's a slightly hacky way to do it as it relies on having set "On Error Resume Next", but you could do something like this:

On Error Resume Next
Dim objRef1, objRef2
Set objRef1 = GetRef("DoStuff1")
If objRef1 Is Nothing Then
    Call objRef1
Else
    MsgBox "DoStuff1 is not defined!"
End If

Set objRef2 = GetRef("DoStuff2")
If objRef2 Is Nothing Then
    MsgBox "DoStuff2 is not defined!"
Else
    Call objRef2
End If

Sub DoStuff1
    MsgBox "DoStuff1!"
End Sub

The call to GetRef will generate an exception if the sub or function you're trying to get a pointer to does not exist (as is the case here with DoStuff2). You can then check if the reference was set as expected.

Siltstone answered 28/5, 2009 at 15:27 Comment(1)
Otherwise you're into checking Err.Number after trying to call the function. But then the function you're calling may be defined, get called, but be the source of the error, which I guess is not what you want.Siltstone
P
0

The provided answers are correct, I just made a simple modification by adding Err.Clear and compacted the function based on the answers provided.

I also renamed the function to a more appropriate name to reflect the fact that it can be used to check the existence of both functions and subroutines.

Function ProcExists(ByVal ProcName)

 On Error Resume Next
  Set ProcName = GetRef(ProcName)
  ProcExists   = (Err.Number = 0)
  Err.Clear
 On Error GoTo 0

End Function
Protoplast answered 17/2, 2021 at 11:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.