[英]Using On Error Goto to try to find why I am getting an error
運行代碼時出現類型不匹配。 有沒有辦法使用 On Error Goto 來幫助我調試它? 這是我的代碼。
Private Sub FH_CNC_HideOrders_Click()
On Error GoTo errHandler
If Me.FH_CNC_HideOrders.Caption = "Hide" Then
'Intiansiate objects and setup variables
Dim tbl As ListObject
Dim c As Range
Dim colStartDate As Range
Dim FoundDate As Date
'Set object/variable values
Set tbl = ActiveWorkbook.Worksheets("Production Tracking").ListObjects("Table293")
With tbl
'Search "Start Date" (Col2), top to bottom, searching for the first cell with a color index of 15 and the "End Date" (Col3) which has an index color of anything other than 15
Set colStartDate = .ListColumns("CNC Begins").DataBodyRange
For Each c In colStartDate.Cells
'MsgBox "c.Value:" & c.Value & " | c.Interior.ColorIndex:" & c.Interior.ColorIndex & " | c.Address:" & c.Address _
& Chr(10) & Chr(10) & "c.Offset.Value):" & c.Offset(0, 1).Value & " | c.Interior.ColorIndex:" & c.Offset(0, 1).Interior.ColorIndex & " | c.Address:" & c.Offset(0, 1).Address
If c.Interior.ColorIndex = 15 And c.Offset(0, 1).Interior.ColorIndex <> 15 Then
FoundDate = c.Value
Exit For
End If
Next c
For Each c In colStartDate.Cells
If Not c.EntireRow.Hidden = True Then
errHandler:
Msbox c.Value
Exit Sub
'Hide dates prior to colStartDate but not empty cells
If Not IsEmpty(c.Value) Then
If Not c.Value >= FoundDate And IsDate(c.Value) Then
c.EntireRow.Hidden = True
'MsgBox c.Address
End If
End If
End If
Next c
End With
Me.FH_CNC_HideOrders.Caption = "Show"
ElseIf Me.FH_CNC_HideOrders.Caption = "Show" Then
Me.FH_CNC_HideOrders.Caption = "Hide"
End If
End Sub
我在代碼中放置了一條注釋,如果發生錯誤,我希望在其中使用MsgBox
值。
你“可以”但我真的不明白你為什么“應該”。
如果您可能因為c
持有非日期而得到不匹配錯誤,為什么不測試c
並找出答案?
If IsDate(c.Value) Then ...
或者也許不是測試它是否是日期,而是找出它是哪幾天類型?
Select Case VarType(c.Value)
Case 2 to 6
MsgBox "These are not dates"
Exit Sub
Case 7
c.EntireRow.Hidden = True
Case Else
....
或者,如果您不想打擾那些 VBA 常量...
If TypeName(c.Value) = "String" Then MsgBox "This is not a date"
讓我們清楚這一點。 錯誤處理不應用於查找代碼問題。 VBA 在這方面已經做得很好,並且會停止程序或拒絕編譯。
錯誤處理是針對異常的,即當您使用超出您控制范圍的資源時,這可能會導致您的程序崩潰而不是您自己的錯誤。 在這種情況下,您應該捕獲錯誤並決定如何處理它。
要消除代碼中的邏輯錯誤,請確保您已完成以下操作。
從代碼中刪除任何 on Error 語句。
您在每個模塊/類的開頭都有 Option Explicit
您可以執行 Debug.Compile 項目而不會出現任何錯誤。
您已經安裝了出色的 RubberDuck 插件並更正了它找到的所有代碼檢查結果。
您現在應該處於這樣一種情況:您處理的唯一錯誤是由外部事件(異常)引起的錯誤。
對於這些最終錯誤,不要使用您在許多示例中看到的(以及在您的代碼中使用的)典型的 On error goto 錯誤處理類型。 而是封裝可能在 On Error Resume Next 和 On Error GoTo 0 之間產生錯誤的行:從而模擬在其他眾所周知的編程語言中看到的“Try catch”結構。
本文提供了有關錯誤處理最佳實踐的良好信息https://rubberduckvba.wordpress.com/2019/05/
在上述第 4 項中,您最有可能發現自己犯的任何細微錯誤。
祝你好運
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.