Try this
Option Explicit
Private Sub uploadData()
Dim oCnn As ADODB.Connection
Dim oRs As ADODB.Recordset
Dim sSQL As String, sCnn As String
Dim rsRow As Long, rsCol As Long
Dim aData As Variant
' Connection string, Change Data Source=C:\mydatabase.mdb to your needs
' Works for access 2003. If you have access 2007 or higher use
' Microsoft.ACE.OLEDB.12.0 and .accdb
sCnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Mike\Desktop\db1.mdb"
' Create Connection Object
Set oCnn = New ADODB.Connection
' Open Created Connection
On Error Resume Next
oCnn.Open sCnn
' Check Connection State.
If oCnn.State <> adStateOpen Then
MsgBox "File Not found: " & vbCrLf & oCnn.ConnectionString, vbCritical
Exit Sub
End If
On Error GoTo 0
' Your Table
sSQL = "tblmain"
Set oRs = New ADODB.Recordset
' Open Created Recordset
On Error Resume Next
oRs.Open sSQL, oCnn, adOpenStatic, adLockOptimistic
If oRs.State <> adStateOpen Then
MsgBox "Could not table: " & sSQL, vbCritical
oCnn.Close
Set oCnn = Nothing
Exit Sub
End If
On Error GoTo 0
' Call to get data from excel sheet.
' Param 1 Path
' Param 2 File Name
' Param 3 Sheet name
aData = GetExcelData("C:\Users\Mike\Desktop\", "Example dummy data ", "Orphans")
For rsRow = LBound(aData, 2) To UBound(aData, 2)
With oRs
.AddNew
.Fields("dbgID") = aData(0, rsRow)
.Fields("Title") = aData(1, rsRow)
.Fields("First name") = aData(2, rsRow)
.Fields("Surname") = aData(3, rsRow)
.Fields("Address 1") = aData(4, rsRow)
.Fields("Address 2") = aData(5, rsRow)
.Fields("Address 3") = aData(6, rsRow)
.Fields("Address 4") = aData(7, rsRow)
.Fields("Address 5") = aData(8, rsRow)
.Fields("Address 6") = aData(9, rsRow)
.Fields("Postcode") = aData(10, rsRow)
.Fields("Campaign code") = aData(0, rsRow) & "_" & aData(11, rsRow)
.Update
End With
Next
' Close Recordset
oRs.Close
Set oRs = Nothing
' Close Connecton
oCnn.Close
Set oCnn = Nothing
End Sub
Public Function GetExcelData(sPath As String, sFileName As String, sSheetName As String) As Variant
Dim sCnn As String
sCnn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sPath & sFileName & ".xls;Extended Properties=""Excel 8.0;HDR=Yes"""
Dim oCnn As ADODB.Connection
Set oCnn = New ADODB.Connection
oCnn.Open sCnn
Dim sSQL As String
sSQL = "SELECT * FROM [" & sSheetName & "$]"
Dim oRs As ADODB.Recordset
Set oRs = New ADODB.Recordset
With oRs
.Open sSQL, oCnn
If Not .EOF Then
GetExcelData = .GetRows
End If
.Close
End With
Set oRs = Nothing
oCnn.Close
Set oCnn = Nothing
End Function
Bookmarks