【问题标题】:Is there a 'On Error Resume Next' function that also logs errors in VBA?是否有在 VBA 中也记录错误的“On Error Resume Next”功能?
【发布时间】:2021-04-22 02:02:12
【问题描述】:

我的代码可以查看 Excel 表格。

Sub ErrorCheck()
    Dim ErrColl As New Collection
    Dim NameColl As New Collection
    Worksheets(WorksheetName).Select           
    Worksheets(WorksheetName).Range("B5").Select
    Do Until IsEmpty(ActiveCell)
        On Error Goto eh
        NameColl.Add ActiveCell.Value
        ActiveCell.Offset(0, 1).Select
    Loop
    eh:
       ErrColl.Add ActiveCell.Value
End Sub

一旦出现重复,上述操作将停止。我不希望代码在发生重复时停止,因为我需要将所有重复项显示在 msgbox/logged 到文件中。 “继续下一个”会给我没有重复的正确答案,但不会显示重复的位置。 'GoTo' 只会显示第一个错误。有没有其他方法可以做到这一点?

【问题讨论】:

标签: excel vba


【解决方案1】:

您始终可以将“On Error Resume Next”与错误代码检查结合使用。以下(非常愚蠢的)代码应该说明这是如何工作的:

On Error Resume Next

Dim i As Integer
Dim m As Integer
Dim n As Double


For i = 1 To 10

    m = i Mod 3
    n = i / m
    If Err.Number > 0 Then
        MsgBox ("Handle error here")
        Err.Number = 0
    Else
        MsgBox ("n: " + Str(n))
    End If
Next

这样做是为了在可能发生错误后测试该行的错误代码。如果没有错误 (Err.Number = 0),则代码继续执行 Else。如果出现错误(在这种情况下 Err.Number = 11 - 当 i 为 3、6 和 9 时除以零),那么您可以在 If 中处理错误,并且代码在 End If 之后继续。请注意,您需要将 Err.Number 重置回 0!

【讨论】:

    【解决方案2】:

    我不会选择太多东西,因为它会减慢您的代码速度。

    无论如何,这里有一些可能有用的东西。必要时更改代码。

    Sub ErrorCheck()
        Dim rCell As Range
        Dim lRow As Long
        Dim rCheck
        
        With Worksheets(1) 'change to suit
            
            Set rCell = .Cells(5, 2)
            
            Set rCheck = rCell
            
            lRow = 1
            
            Do Until rCell(lRow).Value = vbNullString
            
                Set rCheck = Union(rCheck, rCell.Offset(lRow))
                
                With rCell.Offset(lRow)
                
                    If WorksheetFunction.CountIf(rCheck, .Value) > 1 Then
                            
                        Debug.Print .Address & vbTab & .Value 'using the Immediate Window as an example
                                            
                    End If
                
                End With
                
                lRow = lRow + 1
                
            Loop
            
        End With
        
        Set rCell = Nothing
        
        Set rCheck = Nothing
        
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 2019-09-08
      • 1970-01-01
      相关资源
      最近更新 更多