在循环中使用SQL查询的自动化错误

时间:2016-07-29 15:29:05

标签: sql excel-vba vba excel

我试图在一个表中运行循环,该表获取相关信息,然后将其插入到VFP9 .dbf表中。但是,我一直收到自动化错误(' -2147217913(80040e07)')。它似乎第一次运行就好了,在错误输出之前一次插入表中。我每次都将代码的执行部分注释掉,打印出字符串,但SQL看起来非常好。这是什么问题?

Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String

sConnString = "DSN=Visual FoxPro Tables;UID=;SourceDB=s:\accounting\db;SourceType=DBF;Exclusive=No;BackgroundFetch=Yes;Collate=Machine;Null=Yes;Deleted=Yes;"

Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString

For i = 1 To [RawTable].Rows.Count
        vStatement = "dong!"
        vAccount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("account").Index)
        vCardUser = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("card member").Index)
        vDate = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("date").Index)
        vDesc = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("description").Index)
        vAmount = ActiveSheet.ListObjects("RawTable").DataBodyRange.Cells(i, ActiveSheet.ListObjects("RawTable").ListColumns("amount").Index)

        MsgBox "INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")"

        conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "','" & vDate & "','" & vDesc & "'," & vAmount & ")")
Next i
MsgBox "done :)", vbInformation
If CBool(conn.State And adStateOpen) Then conn.Close
Set conn = Nothing

编辑:以下是表格的示例。

date       receipt  description card member account #          amount   account
07/01/2016          Purchase     Employee   XXXX-XXXXXX-XXXXX   9.95    41000-000-00
07/01/2016          Purchase     Employee   XXXX-XXXXXX-XXXXX   33      41000-000-00
06/29/2016          Purchase     Employee   XXXX-XXXXXX-XXXXX   64      41000-000-00

1 个答案:

答案 0 :(得分:0)

Visual Foxpro不希望仅将日期视为String文字或一系列数字。尝试使用CTOD函数(字符到日期),看看是否能解决问题。 Execute行应如下所示:

conn.Execute ("INSERT INTO amex_dist (Statement,Account,Card_user,Date,Desc,Amount) VALUES ('" & vStatement & "','" & vAccount & "','" & vCardUser & "',CTOD('" & vDate & "'),'" & vDesc & "'," & vAmount & ")")