从Excel VBA运行工作参数化的Access SQL查询(INSERT INTO)时出现“需要对象”错误

时间:2015-05-21 12:20:33

标签: sql vba excel-vba ms-access dao

我正在Excel文件中运行一些VBA,以便在Excel中进行数据操作后更新Access数据库。它通过DAO链接创建并执行SQL行。有时,要输入的数据包含破坏SQL的字符(例如INSERT INTO语句的值中的撇号),因此错误捕获参数化查询语句会尝试进行这些更改。

清除旧错误后,查询语句在运行时返回错误“Object required”,但它确实有效(数据库以正确的方式修改)。问题是:为什么它会返回此错误并且我做错了什么?这可能是一个问题吗?

初始错误的代码摘要:

Dim TableName As String, FieldString As String
Dim strSQL As String, valstring As String
Dim NewTableRef As Range
Dim rs As DAO.Recordset, ws As DAO.Workspace, db As DAO.Database

' Fieldstring is a string containing all field names for the table to be changed'
' TableName is the table to be changed'
' Connecting to database and setting ranges done previously'
' strSQL is initially set by the type of change to make'

' modify the recordset'
On Error Resume Next
db.Execute (strSQL)

If Err <> 0 Then
    ' Only an issue for inputs to Table1'
    If TableName = "Table1" Then
        ' try it with parameters'
        strSQL = "PARAMETERS @var1 TEXT, @var2 TEXT, @var3 TEXT, @var4 TEXT, @var5 TEXT;" _
            & "INSERT INTO " & TableName & " (" & FieldString & ") " & " VALUES (@var1,@var2,@var3,@var4,@var5);"

        Set qdf = db.CreateQueryDef("", strSQL)

        qdf!var1 = NewTableRef.Offset(Row - NewTableRef.Row, 1).Value
        qdf!var2 = NewTableRef.Offset(Row - NewTableRef.Row, 2).Value
        qdf!var3 = NewTableRef.Offset(Row - NewTableRef.Row, 3).Value
        qdf!var4 = NewTableRef.Offset(Row - NewTableRef.Row, 4).Value
        qdf!var5 = NewTableRef.Offset(Row - NewTableRef.Row, 5).Value

        Err.Clear
        Error.Clear

        qdf.Execute

        If Err <> 0 Then
            With ThisWorkbook.Sheets("DB Error Log").Range("Error_Log")
                .Columns(1).Offset(ErrNum).Value = Now()
                .Columns(2).Offset(ErrNum).Value = ii
                .Columns(3).Offset(ErrNum).Value = TableName
                .Columns(4).Offset(ErrNum).Value = PKey
                .Columns(5).Offset(ErrNum).Value = Error(Err)
                .Columns(6).Offset(ErrNum).Value = valstring
                ErrNum = ErrNum + 1
                Debug.Print ErrNum
            End With
        End If


    Else

        ' write error has occurred'
        ' log this error'
        With ThisWorkbook.Sheets("DB Error Log").Range("Error_Log")
            .Columns(1).Offset(ErrNum).Value = Now()
            .Columns(2).Offset(ErrNum).Value = ii
            .Columns(3).Offset(ErrNum).Value = TableName
            .Columns(4).Offset(ErrNum).Value = PKey
            .Columns(5).Offset(ErrNum).Value = Error(Err)
            .Columns(6).Offset(ErrNum).Value = valstring
            ErrNum = ErrNum + 1
            Debug.Print ErrNum
        End With

        Error.Clear
        Err.Clear

    End If

End If
On Error GoTo 0

1 个答案:

答案 0 :(得分:2)

Error是一个从错误号返回错误描述的函数;它不是一个对象,因此您无法使用Error.Clear - 从代码中删除它。