如果在循环过程中关闭Excel,则会发生错误处理

时间:2018-08-01 16:00:17

标签: excel error-handling vbscript

我正在运行一个循环(如下)以逐行从excel中写入数据。但是,如果在循环过程中关闭了excel,我希望显示一个错误消息框,指出“脚本已终止”。当前,如果我关闭excel,则会收到Windows脚本宿主严重消息错误:“必需的对象:'rw.Cells'

您知道如何防止Windows Script Host错误出现并显示自定义消息框该脚本已被取消吗?我在循环中使用下面的if语句,但它不起作用。

IF语句:

If (Err.Number <> 0) Then
  On Error GoTo 0
  Wscript.Echo "Script Has Been Terminated"
  Wscript.Quit
End If
On Error GoTo 0 

下面是循环:

Sub Main
subGetSession
subGoToScreen "DELP", "********", "0000000001"
Dim rw
Dim TITLE
    TITLE = "Script Completion Confirmation"
Set atlDirectorObject  = CreateObject("atlDirectorObject.atlDirector")
Set objExcel           = createobject("Excel.Application")
Set objExcelWb         = 
objExcel.Workbooks.Open("S:\Scripting\0711_Settlement2.xlsx")
Set objExcelSht        = objExcelWb.Worksheets("Test")
Set oFileObject        = CreateObject("Scripting.FileSystemObject")
rw = 2
objExcel.Visible = True
Do While objExcel.CountA(objExcelSht.Rows(rw)) > 0
    subDoWork objExcelSht.Rows(rw)
    rw = rw + 1

If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo "Script Has Been Terminated"
Wscript.Quit
End If
On Error GoTo 0 

Loop
Msgbox "End of Worksheet Has Been Reached" & chr(13) & "" & chr(13) & "Script 
Completed!", vbOkOnly, TITLE
End Sub

编辑:因此,我尝试实现您在注释中所说的内容。我一定做错了。这不起作用,我在做什么错?这是我到目前为止的内容:

我将变量声明为:

Public runningScript

然后在循环开始时将其设置为true,在循环结束时将其设置为false:

Do While objExcel.CountA(objExcelSht.Rows(rw)) > 0
runningScript  = True
    subDoWork objExcelSht.Rows(rw)
    rw = rw + 1
runningScript  = False
Loop

然后,如果变量runningScript为true,则执行subDoWork:

Sub subDoWork(rw)
If runningScript = True Then
' all the code goes here
Else
subTerminateScript "Script Canceled"
End If
End Sub

然后在excel中,关闭事件前我有以下内容:

Public Sub Workbook_BeforeClose(Cancel As Boolean)
runningScript = False
End Sub

我在做什么错?????

0 个答案:

没有答案