VB脚本如果那么结束语句

时间:2018-06-08 23:46:37

标签: if-statement vbscript

我正在尝试将宏转换为VB脚本,而我遇到的问题是' if..then..end'声明。这是我的代码。

Option Explicit

Public OpenedWB

Dim valueEntered, fileCount
Dim userResponse
Dim NewWB, NewWS
Dim i
Dim OpenedWBName
Dim Found
Dim FSO, txtFILE
Dim HostFolder
Dim dApproved, dPrepared, filearray()
Dim xlApp
Dim xlCalculationManual
Dim xlCalculationAutomatic, msoFileDialogFolderPicker, msoFileDialogViewSmallIcons

xlCalculationManual = -4135: xlCalculationAutomatic = -4105
msoFileDialogFolderPicker = 4: msoFileDialogViewSmallIcons = 7

Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True

Set NewWB = xlApp.Workbooks.Add
NewWB.Windows(1).Visible = True
Set NewWS = NewWB.Worksheets.Add

Set FSO = CreateObject("Scripting.FileSystemObject")

With xlApp
    .ScreenUpdating = False
    .EnableEvents = False
    .Calculation = xlCalculationManual
End With

i = -1

'UI (Dynamic) Directory
With xlApp.FileDialog(msoFileDialogFolderPicker)
    .AllowMultiSelect = False
    .Title = "Select the folder to scan through sub-folders"
    .ButtonName = "Select this folder!"
    .InitialFileName = _
        "\\..somepath"
    .InitialView = msoFileDialogViewSmallIcons
    If .Show <> i Then End  'This is throwing an error (Expected statement error)
    HostFolder = .SelectedItems(1)
End With

我不确定为什么我会收到此错误,因为它在VBA中运行正常,但我猜它是因为我在VBA子程序中有代码。

任何人都可以帮我解决这个问题吗?

由于

2 个答案:

答案 0 :(得分:2)

你的意图是什么?如果您的意思是使用End作为结束程序的语句,那么您应该知道 VBScript中没有End语句only exists in "full-fat" VB6, VBA {{3这是“结束程序”命令(但你不应该使用它,因为它不执行任何程序清理,并且可能导致需要处理的泄漏资源)。

我认为你想要Exit语句。 Exit语句实际上并不完全退出程序,它相当于其他语言中的returnbreak

and VB.NET

  

Exit语句语法具有以下形式:

   Exit Do  
   Exit For  
   Exit Function  
   Exit Property  
   Exit Sub  

很遗憾,您无法在“顶级”脚本程序代码中使用Exit(即在显式SubFunction之外)。我的建议是将您的程序包装在Sub内,而您的顶级程序只需调用Sub即可。

此外,不要将它与Stop语句混淆 - 实际上暂停脚本执行(如断点),直到用户恢复它,因此它不是真正的“停止”执行“命令。它也没有关闭句柄:

https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/scripting-articles/t234253x%28v%3dvs.84%29

  

Stop:暂停执行。
  使用Stop语句类似于在代码中设置断点   Stop语句暂停执行,但它不会关闭任何文件或清除任何变量。

在你的情况下,反转If更简单,就像这样:

With xlApp.FileDialog(msoFileDialogFolderPicker)
    .AllowMultiSelect = False
    .Title = "Select the folder to scan through sub-folders"
    .ButtonName = "Select this folder!"
    .InitialFileName = "\\..somepath"
    .InitialView = msoFileDialogViewSmallIcons
    If .Show = i Then
        Set HostFolder = .SelectedItems(1)
    End If
End With

(我认为必须为HostFolder语句分配Set语句,因为它是Object而不是值,但如果它在没有Set的情况下有效,那就没问题了< / p>

TL; DR:

  • 在VBScript中没有单一的End语句来结束程序执行。它只存在于VB6,VBA和VB.NET中。
  • Stop语句实际上暂停执行,就像断点一样,它不会结束执行。
  • Exit语句仅适用于父控件结构SubFunction,因此在顶级程序中无效。

答案 1 :(得分:0)

If .Show <> i Then WScript.Quit