VBA错误句柄 - 恢复和打印错误

时间:2015-05-28 13:54:41

标签: excel vba excel-vba error-handling

我正在尝试构建如下所示的结构。 我有一个循环,有时其中一个循环步骤可以返回错误但我想跳过它并继续循环直到结束。

但是如果任何循环执行有错误,我想知道它在单元格中打印类似于"缺少负载:(1,20,36)"这个数字是循环中我的一个变量接收的唯一值。

所以我认为每当我的一个循环执行返回错误时,我需要构建一个这个变量值的列表,并在循环过程结束时使用此列表返回此错误信息。

更新

对于下面我想知道任何最终的" sProdId" SQL查询中的值由于任何错误而无法执行。通常它会尝试在数字SQL字段中插入#Value。

    Sub SavetoSQL()

        Dim conn As New ADODB.Connection
        Dim iRowNo As Integer

        Dim Ddate
        Ddate = Range("refdate")

        Dim RngRefdate As Date
        RngRefdate = DateSerial(Year(Ddate), Month(Ddate), Day(Ddate))



 With Sheets("Hist Prods temp")

     'Open a connection to SQL Server
            conn.Open "Provider=SQLOLEDB;Data Source=XXXXX;Initial Catalog=XXXXXX;User Id=XXXX;Password=XXXXXXX;"

            'Skip the header row
            iRowNo = 2

            'Loop until empty cell in sRefDate
            Do Until .Cells(iRowNo, 1) = ""
                sRefDate = .Cells(iRowNo, 1)
                sProdId = .Cells(iRowNo, 2)
                sPrice = .Cells(iRowNo, 3)
                sValue = .Cells(iRowNo, 4)
                sDV01 = .Cells(iRowNo, 5)
                sDelta1 = .Cells(iRowNo, 6)
                sDeltaPct = .Cells(iRowNo, 7)
                sGamma = .Cells(iRowNo, 8)
                sVega = .Cells(iRowNo, 9)
                sTheta = .Cells(iRowNo, 10)
                sDelta2 = .Cells(iRowNo, 11)
                sIVol = .Cells(iRowNo, 12)

'Generate and execute sql statement to import the excel rows to SQL Server table

conn.Execute "INSERT INTO [dbo].[Prices] ([Date],[Id_Product],[Price],[Value],[DV01],[Delta1$],[Delta%],[Gamma$],[Vega$],[Theta$],[Delta2$],[Ivol],[Last_Update]) values ('" & sRefDate & "', '" & sProdId & "'," & sPrice & "," & sValue & "," & sDV01 & "," & sDelta1 & "," & sDeltaPct & "," & sGamma & "," & sVega & "," & sTheta & "," & sDelta2 & "," & sIVol & ",GETDATE())"


 iRowNo = iRowNo + 1

 Loop

 conn.Close
 Set conn = Nothing

 End With

 End Sub

2 个答案:

答案 0 :(得分:0)

您对VBA中的错误处理感到有点困惑,请查看Chip的网站Error Handling in VBA

您的代码应该是类似的,

Sub MyMacro()
On Error GoTo Errhandler
    Dim errLog As String
    Do Until
        ' My loop code
        'Save variable X value in a list of error values.
    Loop
ExitErrHandler:
    If Len(errLog) > 0 Then
        Range("M2") = "Missing loads: (" & Left(errLog, Len(errLog) - 2) & ")"
    End If 
    Exit Sub

Errhandler:
    'Make a Note of the Error Number and substitute it with 1234
    If Err.Number = 1234 Then
        ' If an error occurs, display a message in a cell with all X values on the list.
        errLog = errLog & yourUniqueValue & ", "
        Resume Next
    Else
        MsgBox "Another Error occurred." & vbCrLf & vbCrLf & Err.Number & " - " & Err.Description
        Resume ExitErrHandler
    End If
End Sub

答案 1 :(得分:0)

您的代码没有任何意义,因为在您遇到会引发错误的循环代码之前,您正在关闭错误处理(On Error GoTo 0)。

这是一种方法。我在循环中有我的错误处理程序。它将x值附加到字符串。由于x = x + 1位于错误处理程序中,因此当您收到错误时,不必担心x不会递增。如果您只关心某些Err.Number值,请更改错误处理程序中的if语句。在代码的最后,我将错误消息打印到A1的单元Sheet2当且仅当错误消息字符串至少有一个值时。否则我重置该输出单元格。 On Error GoTo -1对于重置错误处理程序非常重要。

Sub MyMacro()
    Dim x As Integer
    Dim errMsg As String
    Dim outWs As Worksheet
    Set outWs = ThisWorkbook.Worksheets("Sheet1")
    errMsg = ""

    On Error GoTo CurrRecFail
    x = 1
    Do Until x = 15
        ' My loop code

CurrRecFail:
        If Err.Number > 0 Then
            errMsg = errMsg & x & ", "
        End If
        On Error GoTo -1
        x = x + 1

    Loop

    If Len(errMsg) > 0 Then
        outWs.Cells(1, 1).Value = "Missing Loads: " & Left(errMsg, Len(errMsg) - 2)
    Else
        outWs.Cells(1, 1).Value = ""
    End If

End Sub

上面的代码会在遇到错误时跳转到下一个循环迭代。如果您希望继续执行当前循环迭代中的其余行,请将On Error GoTo CurrRecFail更改为On Error Resume Next并删除现在是无意义标记的行CurrRecFail: