What is the code to exit/ stop VBscript from running in the event of a condition not being met?

I've found that the WScript is always available if running a .vbs/.vbe/.wsf script using either the wscript.exe or cscript.exe engine. When WScript is not available is if running using a different engine. E.g. running VBScript within a HTA, a webpage, in VBA or from a hosted COM script control.

To exit a script which is not running from wscript.exe or cscript.exe, you can do something like the following:

main

Sub main
    ' execute code here

    ' oops a confition is not met:
    If Not condition then Exit Sub

    ' more code to execute if condition was met
End Sub

You can use something like this:

Sub MyFunc
    ----------
    My Code
    ----------
End Sub

Function Main
  On Error Resume Next
  MyFunc
  If Err.Number <> 0
  Exit Function
End Function

It'll stop executing the code, the point it finds an exception or throws an error.


The Wscript object is only available if you are running in the Windows Script Host (wscript.exe,cscript.exe). NOT Internet Explorer (iexplorer.exe, mshta.exe)

Well an easy way to do this is to declare a global variable that gets set to false until an error occured, and if the error occured then that variable will be set to true, after that anytime that variable gets checked you can exit sub\function\for\do\whatever.

Example:

Dim ErrorOccured
On Error Resume Next
ErrorOccured=False


Sub Main()
    If ErrorOccured Then Exit Sub
    'some code
    MsgBox "Main has run"
End Sub


Sub MakeAnError
    If ErrorOccured Then Exit Sub
    'some code
    Err.Raise 2
    If Err Then ErrorOccured=True
End Sub


Function TellMeRandom
    If ErrorOccured Then Exit Function
    'some code
    Randomize
    TellMeRandom =Int((100- 1+ 1) * Rnd + 1)*1
End Function


Function ResetError
    ErrorOccured=False
End Function



Call Main                 'Main will run because an error has not occured (ErrorOccured is False)

MsgBox TellMeRandom       'This will return a random number 1-100

Call MakeAnError          'This will set the Global ErrorOccured to true

MsgBox TellMeRandom       'This will be blank because the ErrorOccured prevented it from running

Call Main                 'This will not run because the ErrorOccured prevented it from running

Call ResetError           'This will set the Global ErrorOccured to false

Call Main                 'This will run because ErrorOccured is back to False

MsgBox TellMeRandom       'This will return a random number 1-100 because ErrorOccured is back to false

Just remember to Add If ErrorOccured then Exit Sub for a sub routine or If ErrorOccured then Exit Function for a function.

Tags:

Vbscript