【发布时间】:2018-03-26 05:15:22
【问题描述】:
我对 Excel VBA 很陌生,并且在错误处理程序方面遇到了麻烦(使用 On Error Goto [label])。我的代码有点遵循这个流程:
StartDate = Format(Cells(11, 4).Value, "yyyy-mm-dd")
EndDate = Format(Cells(12, 4).Value, "yyyy-mm-dd")
For Each WS In Worksheets
If WS.Name Like "WS_Name" Then
Exist = True
Exit For
End If
Next
On Error GoTo EHandler: '[ERROR HANDLER POINT A]
If Exist = True Then
On Error GoTo EHandler: '[ERROR HANDLER POINT B]
ActiveWorkbook.Sheets("WS_Name").Select
Sheets("WS_Name").Cells.ClearContents
With 'some code that uses the StartDate and EndDate in a SQL query in a database
End With
Else
ActiveWorkbook.Worksheets.Add.Name = "WS_Name"
With 'some code that uses the StartDate and EndDate in a SQL query in a database
End With
End If
Exit Sub
EHandler:
'some code that would show the error number and desc
End Sub
我想为用户可能输入比我的 StartDate 更早的 EndDate 的事件设置错误处理程序。我尝试在 ERROR HANDLER POINTS A & B 上插入 On Error Goto [label] 并得到不同的结果。
如果我的 On Error Goto [label] 位于 POINT A,则 EHandler 不起作用。
如果我的 On Error Goto [label] 在 POINT B 上,即使输入的日期正确,EHandler 也会工作。
我该如何处理这个?
【问题讨论】:
-
不应该
EndDate = 'some code知道StartDate以便提前完成检查吗? -
If Exist = True Then变为If Exist Then和ActiveWorkbook.Sheets("WS_Name").Select : Sheets("WS_Name").Cells.ClearContents变为ActiveWorkbook.Sheets("WS_Name").Cells.ClearContents(至少!)。