[英]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.