ADO参数查询将相同的数据插入每一行

时间:2014-05-04 12:46:26

标签: sql excel vba ms-access-2010 ado

我有以下代码将几行excel数据输入到Microsoft Access数据库中。代码似乎正在工作,数据正在写入数据库。唯一的问题是,只输入了第一行数据!

foo

这是我的代码:

Sub AddToDB()
Dim adoConn As ADODB.Connection
Dim adoComm As ADODB.Command
Dim RecordRow As Long
Dim TheProduct As String, TheQuantity As String, ThePrice As Double
Dim Location As String, TheTime As Date, SaleNumber As Integer

Set adoConn = GetConnectionTWO
Set adoComm = New ADODB.Command
Lastrow = Sold.Cells(Rows.Count, 1).End(xlUp).Row
Location = Frontsheet.Range("M3").Value

        With adoComm
                Set .ActiveConnection = adoConn

                    For RecordRow = 2 To Lastrow

                            SaleNumber = Sold.Cells(RecordRow, 1).Value
                            TheTime = Sold.Cells(RecordRow, 5).Value
                            TheProduct = Sold.Cells(RecordRow, 2).Value
                            TheQuantity = Sold.Cells(RecordRow, 3).Value
                            ThePrice = Sold.Cells(RecordRow, 4).Value

                            .CommandText = "INSERT INTO Sales([SaleNo],[Time],[Location],[Product],[Quantity],[Price]) " & _
                                          "VALUES(?,?,?,?,?,?)"

                            .Parameters.Append adoComm.CreateParameter(Type:=adInteger, Value:=SaleNumber)
                            .Parameters.Append adoComm.CreateParameter(Type:=adDate, Value:=TheTime)
                            .Parameters.Append adoComm.CreateParameter(Type:=adVarWChar, Size:=255, Value:=Location)
                            .Parameters.Append adoComm.CreateParameter(Type:=adVarWChar, Size:=255, Value:=TheProduct)
                            .Parameters.Append adoComm.CreateParameter(Type:=adVarWChar, Size:=255, Value:=TheQuantity)
                            .Parameters.Append adoComm.CreateParameter(Type:=adDouble, Value:=ThePrice)

                            .Execute

                    Next RecordRow    
        End With

            adoConn.Close
End Sub


Function GetConnectionTWO() As ADODB.Connection
    Set GetConnectionTWO = New ADODB.Connection
    GetConnectionTWO.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" &  PathToDatabaseTWO & ";"
End Function

Function PathToDatabaseTWO() As String
PathToDatabaseTWO = ThisWorkbook.Path & "\" & "kimpostwo.accdb"
End Function

我认为" For - Next"循环我将移动到下一行,当我单步执行excel VBA编辑器中的代码时,我可以看到数据发生变化。

我尝试在.parameter.append行之前和之后移动.commandtext行,但仍然没有变化。

我对使用ADO非常陌生,并希望能指出我需要做什么。

1 个答案:

答案 0 :(得分:3)

不是在for循环中反复添加所有参数,而是尝试仅创建一次命名参数,并仅在调用Excecute()之前更改其值。 ' SaleNumber'的示例:

With adoComm
    Set .ActiveConnection = adoConn
    .CommandText = "INSERT INTO Sales([SaleNo]) VALUES(?)"
    .Parameters.Append adoComm.CreateParameter("SaleNumber", Type:=adInteger)

    For RecordRow = 2 To Lastrow

        SaleNumber = Sold.Cells(RecordRow, 1).Value

        .Parameters("SaleNumber").Value = SaleNumber
        .Execute

    Next RecordRow
End With