Reputation: 3845
I have the following code to enter several rows of excel data into a microsoft Access database. The code appears to be working and data is being written to the database. The only problem is, only the first row of data is being entered, several times!
Here is my code:
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
I thought the "For - Next" loop i have would move to the next row, and when i step through the code in the excel VBA editor, i can see the data changing.
Ive tried moving the .commandtext line before and after the .parameter.append lines but still no change.
I'm very new to using ADO and would appreciate a pointer on what i need to do.
Upvotes: 2
Views: 1518
Reputation: 14053
Instead of addind all parameters again and again in the for-loop try to create the named parameter only once and change its value only before Excecute() is called. Example for '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
Upvotes: 3