如果条件不满足,退出/停止VBscript运行的代码是什么?

时间:2012-11-21 23:40:15

标签: vbscript

我看过谷歌并且答案不存在!

首先要做的事情。 WScript.Quit不工作!我不知道“WScript”是什么,但它显然与网页的客户端脚本无关。我以前在某处看过这个“WScript”的东西而且它只会产生错误(可能是过时的或者其他的东西)所以请不要建议......

无论如何......我想做的就是在条件不满足的情况下完全停止脚本。显然我不想要“Exit Sub”,因为如果嵌入了该子代码,代码将继续运行!

我知道“停止”命令,但我的印象是它只用于调试。

希望这是一个非常简单的问题。

更新和结论:在我结束这个主题之前,我将稍微展开一下我想要做的事情......

我有一些按钮点击启动的主要潜艇。为了使我不需要编辑每个单独的子,我在每个子中嵌入了一个通用子进行初步检查。

初步检查的一部分是在用户输入不正确的情况下停止程序。如果检测到错误,我想暂停从那一点开始的所有进展。 “退出子”显然只会跳过该初步子的其余部分,主子将继续执行。

最后,它只是写入错误标志(在主要子系统中检查)或在每个主程序中包含错误条件操作的情况。以这种方式退出主要子,问题就解决了。

这不是懒惰 - 我只是想减少代码量。无论如何,谢谢你的回复。

5 个答案:

答案 0 :(得分:9)

我发现如果使用wscript.exe或cscript.exe引擎运行.vbs / .vbe / .wsf脚本,WScript始终可用。当WScript不可用时,如果使用其他引擎运行。例如。在HTA,网页,VBA或托管的COM脚本控件中运行VBScript。

要退出未从wscript.exe或cscript.exe运行的脚本,您可以执行以下操作:

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

答案 1 :(得分:7)

您可以使用以下内容:

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

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

它将停止执行代码,它发现异常或抛出错误。

答案 2 :(得分:3)

仅当您在Windows脚本宿主(wscript.exe,cscript.exe)中运行时,Wscript对象才可用。不是Internet Explorer(iexplorer.exe,mshta.exe)

这样做的一个简单方法是声明一个全局变量,该变量设置为false直到发生错误,如果发生错误,那么该变量将设置为true,之后任何时候检查该变量都可以退出子\功能\为\ DO \不管。

示例:

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

请记住为子例程添加If ErrorOccured then Exit Sub或为函数添加If ErrorOccured then Exit Function

答案 3 :(得分:1)

最简单的方法是,我发现的是:WScript.Quit

答案 4 :(得分:0)

您还可能引发错误,例如: Err.Raise 507

这将退出当前脚本:&#34;发生异常&#34;