Shawn V. Wilson
Shawn V. Wilson

Reputation: 1111

In VBScript, can I raise an error to simulate Goto?

If I were working in VBA, my current procedure would go something like this:

Do While MyFile.AtEndOfStream <> True
arrRecord = Split(MyFile.ReadLine, ",") ' Make an array of the values in this line

'There are certain records I don't want to process:
If arrRecord(1) <> "USA" then goto skip
If arrRecord(0) <= "12/31/2001" then goto skip

' Otherwise, run the rest of the code on this record

skip:
Loop

But I'm working in VBScript, which doesn't have this kind of Goto function.

I'm thinking of doing the same thing by delibaratly raising an error. For instance:

Do While MyFile.AtEndOfStream <> True
arrRecord = Split(MyFile.ReadLine, ",") ' Make an array of the values in this line

On Error Goto skip

'There are certain records I don't want to process:
If arrRecord(1) <> "USA" then Call NoSuchFunction
If arrRecord(0) <= "12/31/2001" then Call NoSuchFunction

' Otherwise, run the rest of the code on this record

skip:
Loop

Is there any potential problem with this? Should I use Err.Raise instead?

Upvotes: 1

Views: 923

Answers (2)

user65839
user65839

Reputation:

VBScript, unlike VBA, doesn't have On Error Goto. It only has On Error Resume Next.

However, the case that you're looking for, of exiting a control flow early, can be handled with the Exit statement. See this article from the Microsoft Scripting Guys for more details and examples.

If you're not currently in a control flow that you are looking to exit, you can hack it by creating one that will only execute once:

Do
    'Stuff
    If something Then Exit Do
    'More Stuff
Loop While False 'Execute once, can be left early by "Exit Do"

And while that's clearly a hack, I'm not sure it's any worse than trying to use a straight "Goto" in the first place. Usually one can restructure the logic to be clear as to what one is actually doing, without needing such inelegant constructs.

Upvotes: 2

rory.ap
rory.ap

Reputation: 35270

This is not possible in VBScript. The only error handling you have is On Error Resume Next and, to disable that within a certain scope, On Error Goto 0.

There's no such think as a label in VBScript.

Upvotes: 1

Related Questions