我正在尝试将宏转换为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子程序中有代码。
任何人都可以帮我解决这个问题吗?
由于
答案 0 :(得分:2)
你的意图是什么?如果您的意思是使用End
作为结束程序的语句,那么您应该知道 VBScript中没有End
语句,only exists in "full-fat" VB6, VBA {{3这是“结束程序”命令(但你不应该使用它,因为它不执行任何程序清理,并且可能导致需要处理的泄漏资源)。
我认为你想要Exit
语句。 Exit
语句实际上并不完全退出程序,它相当于其他语言中的return
和break
:
Exit语句语法具有以下形式:
Exit Do Exit For Exit Function Exit Property Exit Sub
很遗憾,您无法在“顶级”脚本程序代码中使用Exit
(即在显式Sub
或Function
之外)。我的建议是将您的程序包装在Sub
内,而您的顶级程序只需调用Sub
即可。
此外,不要将它与Stop
语句混淆 - 实际上暂停脚本执行(如断点),直到用户恢复它,因此它不是真正的“停止”执行“命令。它也没有关闭句柄:
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>
End
语句来结束程序执行。它只存在于VB6,VBA和VB.NET中。Stop
语句实际上暂停执行,就像断点一样,它不会结束执行。Exit
语句仅适用于父控件结构Sub
或Function
,因此在顶级程序中无效。答案 1 :(得分:0)
If .Show <> i Then WScript.Quit