在VBScript中,我可以引发错误来模拟Goto吗?

时间:2016-08-08 17:53:44

标签: vbscript

如果我在VBA工作,我目前的程序将是这样的:

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

但是我在VBScript中工作,它没有这种Goto功能。

我想通过delibaratly引发错误来做同样的事情。例如:

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

这有什么潜在的问题吗?我应该使用Err.Raise吗?

2 个答案:

答案 0 :(得分:2)

与VBA不同,VBScript没有On Error Goto。它只有On Error Resume Next

但是,您可以使用Exit语句处理您提前退出控制流的情况。有关详细信息和示例,请参阅Microsoft Scripting Guys中的this article

如果您当前不在要退出的控制流中,可以通过创建只执行一次的控制流来破解它:

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

虽然这显然是一个黑客攻击,但我不确定它是否比尝试使用直接&#34; Goto&#34;更糟糕。首先。通常人们可以重新构造逻辑,以清楚地知道一个人在做什么,而不需要这些不优雅的结构。

答案 1 :(得分:1)

这在VBScript中是不可能的。您唯一的错误处理是On Error Resume Next,并且要在某个范围内禁用On Error Goto 0

在VBScript中没有这样的标签。

相关问题