Insert multiple records using ADO?

SydneyGeek

MrExcel MVP
Joined
Aug 5, 2003
Messages
12,251
Hi, I'm trying to work out how to push multiple records from an Excel range to an Access database using ADO. Mr Excel's VBA book show how to do it one record at a time, but I will have anything up to 2000 records to push (about 35 fields) and one at a time will take forever...
Here's my starting code, but I am not sure of the syntax for the SQL statement, and how to actually push the data (or even if a bulk update is possible with ADO).

TPath and DataLoader are named ranges in the workbook. DataLoader is a dynamic range with potentially several thousand rows, depending on the # of projects in the file. The target table is tblProjectData.

I know I don't have a statement that achieves the "Push", but I couldn't work out the syntax. Any pointers appreciated...

Code:
Sub PushDataToMDB()
  Dim cnn As ADODB.Connection
  Dim rst As ADODB.Recordset
  Dim sSQL As String
  Dim sPath As String
  Dim rSource As Range
  Dim MyConn
  
  Set rSource = Range("DataLoader")
  sPath = Range("TPath").Value
  
  sSQL = "INSERT INTO tblProjectdata SELECT * FROM " & rSource
  
  MyConn = sPath
  
  Set cnn = New ADODB.Connection
  With cnn
    .Provider = "Microsoft.Jet.OLEDB.4.0"
    .Open MyConn
  End With
  
  Set rst = New ADODB.Recordset
  rst.CursorLocation = adUseServer
  rst.Open Source:=sSQL, ActiveConnection:=cnn, _
    CursorType:=adOpenForwardOnly, LockType:=adLockOptimistic, _
      Options:=adCmdText
  
  Application.ScreenUpdating = False
 
  rst.Close
  cnn.Close
  
  Application.ScreenUpdating = True


End Sub
 

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.
Hi, thanks for looking...

I tried adding records one at a time, and it turned out to be pretty quick -- 950 records created in about 2 seconds, on a network drive. So I guess the bulk insert isn't essential, though I'd still be interested to know if it was possible.
Here's my working code:
Code:
Sub PushDataToMDB()
  Dim cnn As ADODB.Connection
  Dim rst As ADODB.Recordset
  Dim sSQL As String
  Dim sPath As String
  Dim rSource As Range
  Dim MyConn
  Dim Rw As Long, LastRow As Long
  
  Set rSource = Range("DataLoader")
  LastRow = rSource.Rows.Count
  
  sPath = Range("TPath").Value
  
  MyConn = sPath
  
  Set cnn = New ADODB.Connection
  With cnn
    .Provider = "Microsoft.Jet.OLEDB.4.0"
    .Open MyConn
  End With
  
  Set rst = New ADODB.Recordset
  rst.CursorLocation = adUseServer
  rst.Open Source:="tblProjectData", ActiveConnection:=cnn, _
    CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
      Options:=adCmdTable
      
  Application.ScreenUpdating = False
  Application.Goto Range("DataLoader")
  
  For Rw = 2 To LastRow
    ActiveCell.Offset(1, 0).Select
    rst.AddNew
    Application.StatusBar = "Adding Record " & Rw & " of " & LastRow
    
    rst("Project") = Cells(ActiveCell.Row, 1)
    'continue looping thru fields till the last one...
    rst("Version") = Cells(ActiveCell.Row, 34)
    
    rst.Update
  Next Rw
  Application.StatusBar = ""
  rst.Close
  cnn.Close
  
  Application.ScreenUpdating = True


End Sub
Denis
 
Upvote 0
if you're still interested I've been doing this with some fairly large data sets.
what I have found is that anytime you loop in vba code it starts to hit performance big time.
the code you have is going to be way more efficient if you avoid loops by doing things like pulling out ranges from the sheet into arrays and inserting them into the database preferably using a stored procedure(accessed via ado)

all depends on how crucial performance is, a lot of code which works fine fro a few hundred iterations will scale very badly when you go to a few hundred thousand.
 
Upvote 0
I´m not sure but here is an example that may help You:

Code:
Dim cnt As ADODB.Connection
Dim stSQL As String, stCon As String, stDB As String

'Path to and the name of the database
stDB = ThisWorkbook.Path & "\Db1.mdb"

'The connection string.
stCon = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=" & stDB & ";"

'Create the Export-query.
stSQL = "INSERT INTO Table1 SELECT * FROM [DataLoader] IN '" _
        & ThisWorkbook.FullName & "' 'Excel 8.0;'"

'Instantiate the ADODB COM Object.
Set cnt = New ADODB.Connection

With cnt
    .Open stCon
    'Execute the update.
    .Execute (stSQL)
End With

'Close the connection.
cnt.Close

'Release object from memory.
Set cnt = Nothing
 
Upvote 0
Guys, thanks for the updates -- I knew there were likely to be faster ways to do this, but didn't have a handle on the best methods.

alandalmon: The stored procedure method would definitely be the way to go for many thousands of records -- I wouldn't like to loop through that many, but the solution is for up to 2000 records at a time, at least for the moment.

XL-Dennis: Thanks for the SQL syntax. I wasn't sure how to set up a SQL statement instead of looping. I'll try it out to see how it goes.

Hope you both had a great Christmas and New Year.
Denis
 
Upvote 0

Forum statistics

Threads
1,214,832
Messages
6,121,847
Members
449,051
Latest member
excelquestion515

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top