当错误抛出时我正在处理错误跳到下一步。第一次错误正常工作,第二次投掷错误

时间:2018-05-22 09:31:55

标签: excel-vba vba excel

下面的代码在第一次错误但第二次抛出错误时工作正常。我在cn.execute(Sql)收到错误所以我想在得到错误并继续循环时跳到下一步

'EXECUTION OF SQL QUERY
Application.EnableEvents = False
Application.ScreenUpdating = False
'Application.ErrorCheckingOptions.BackgroundChecking = False
    Set Sql = ws.Range("D" & m)
    On Error GoTo errHandler:
    Set Rec_set = cn.Execute(Sql) 'Issue SQL statement
    Status = Worksheets("Count").Range("B" & m).Value
    Application.StatusBar = "Table Executing :" & Status
    While Not Rec_set.EOF
    ws.Range("E" & m).CopyFromRecordset Rec_set
    Wend
    Rec_set.Close 'Close the recordset

           'FILE UPLOAD
'Mention the SHarePoint Address and directly upload into SharePoint
 ws.Range("D" & m & ":" & "E" & m).ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
  "" & sFolder & "/_Count_Row" & m & ".pdf", Quality:= _
    xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
    OpenAfterPublish:=False

    With ws
        .Hyperlinks.Add Anchor:=.Range("F" & m).End(xlUp).Offset(1, 0), _
            Address:="" & sFolder & "/Count_Row" & m & ".pdf", _
            ScreenTip:="Hyperlink", _
            TextToDisplay:="Count_Row" & m
    Application.StatusBar = "File is being uploded into SharePoint for the table :" & Status
    End With
errHandler:
Next m

我在Resume next仍然抛出错误后尝试了errHandler: 谁能在这帮助我?

2 个答案:

答案 0 :(得分:0)

如果您想避免使用Resume Next的错误,那么您也必须清除它们。

因此,在Resume Next之后(或之前)的行上写Err.Clear。这是一个小例子如何使用Err.Clear,虽然它看起来很像意大利面条代码:

Public Sub TestMe()

    Dim cnt As Long
    On Error GoTo TestMe_Error

    For cnt = 1 To 10
        If Err.Number = 0 Then
            If cnt Mod 2 = 1 Then
                Debug.Print cnt / 0
            Else
                Debug.Print cnt / 2
            End If
        End If
    Next cnt

    On Error GoTo 0
    Exit Sub

TestMe_Error:

    Debug.Print "Error " & Err.Number & " (" & Err.Description & ") "
    Err.Clear
    Resume Next

End Sub

答案 1 :(得分:-1)

我使用下面的代码并正常工作:

errHandler:
On Error GoTo -1
Next M

感谢大家的投入。