importing from access using VBA

rogerm

Board Regular
Joined
May 12, 2002
Messages
53
I have been using the following code to export data from excel into an access database.


Sub export()
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
var1 = "export to database complete"
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=\\SERVER19\mainfolder\subfolder\data.mdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "tablename", cn, adOpenKeyset, adLockOptimistic, adCmdTable ' all records in a table
r = 4 ' the start row in the worksheet
Do While Len(Range("B" & r).Formula) > 0 ' repeat until first empty cell in column A
'If Range("Q" & r).Value = "New Item" Then
With rs
.AddNew ' create a new record
.Fields("F1") = Range("B" & r).Value
.Fields("F2") = Range("C" & r).Value
.Fields("F3") = Range("D" & r).Value
.Fields("F4") = Range("E" & r).Value
.Fields("F5") = Range("F" & r).Value
.Fields("F6") = Range("G" & r).Value
.Fields("F7") = Range("H" & r).Value
.Fields("F8") = Range("I" & r).Value
.Fields("F9") = Range("J" & r).Value
.Fields("F11") = Date
.Fields("Sheet_Date") = Range("F36").Value
.Fields("Comp_By") = Range("C38").Value

.Update ' stores the new record

End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
MsgBox var1
End Sub

Does anyone know a way to do the same thing but using a button on access to import the data.

Most of the solutions I have seen only import a whole spreadsheet or a named range which often imports blank rows if there is no data in these rows.

Any help would be greatly appreciated.
 

Excel Facts

Will the fill handle fill 1, 2, 3?
Yes! Type 1 in a cell. Hold down Ctrl while you drag the fill handle.

Forum statistics

Threads
1,221,501
Messages
6,160,175
Members
451,629
Latest member
MNexcelguy19

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