ADODB错误处理变量未设置

时间:2015-02-19 19:40:11

标签: vba ms-access adodb

我构建了一个ADODB错误陷阱,但出于某种原因,errSQL.Number和errSQL.Description都给了我一个" Object变量或With Block变量未设置。"错误....这是我的代码到目前为止...我启用了活动的x对象,我认为.number和.description是正确的...任何帮助都会很棒!我故意运行的查询将发送错误。

当我对错误陷阱进行注释时,我会收到一个带有SQL语法错误的消息框,但似乎无法像下面那样陷阱...

Public errSQL              As ADODB.Error
Public strErrODBC          As String

Private Sub verifySQL()

Dim strSQL2             As String
Dim cn          As New ADODB.Connection
Dim cdTxt               As String
Dim rs                  As New ADODB.Recordset
Dim intVerify           As Integer


On Error GoTo ODBCErrorHandler



cn.ConnectionString = "DSN=source;"

cn.Open

If cn.State = adStateOpen Then

    rs.Open "SELECT CASE WHEN MAX((CASE WHEN " & Forms!dlgSplitName.lstbxFlds.Column(0) & " " & cdTxt & " THEN 1 ELSE 0 END)) =1 THEN 1 ELSE 0 END FROM table;", cn
Else

End If

intVerify = rs.Fields(0).Value

If intVerify = 1 Then

        insrt_Test


    ElseIf intVerify = 0 Then

        MsgBox "No records were found with the code text logic.", vbExclamation + vbOKOnly, "Spliy by Notification"

    End If


ODBCErrorHandler:




    Debug.Print errSQL.Number
    Debug.Print errSQL.Description

  strErrODBC = "A SQL error was encountered with the code text logic." & vbCrLf
  strErrODBC = strErrODBC & "Error " & errSQL.Number & vbCrLf
  strErrODBC = strErrODBC & " " & errSQL.Description


  MsgBox strErrODBC & vbCrLf & "Please try again.", vbCritical, "Split by field code text error."

cn.Close


End Sub

1 个答案:

答案 0 :(得分:3)

问题是errSQL ADODB Error对象永远不会设置为任何东西。 Connection对象具有您需要用于显示错误的错误集合。试试这个:

ODBCErrorHandler:

Dim ErrorCount As Double
Dim strError As String

ErrorCount = cn.Errors.Count
strErrODBC = "A SQL error was encountered with the code text logic." & vbCrLf

If ErrorCount > 0 Then
    For index = 0 To (ErrorCount - 1)
        Set errSQL = cn.Errors.Item(index)

        strErrODBC = strErrODBC & "Error " & errSQL.Number & vbCrLf
        strErrODBC = strErrODBC & " " & errSQL.Description & vbCrLf
    Next index
 End If

MsgBox strErrODBC & vbCrLf & "Please try again.", vbCritical, "Split by field code text error."

cn.Close

希望这有帮助。