Frage

I have been struggling to transfer data from multiple excel worksheets into multiple access tables. So how this goes is this way. I have 5 worksheets and each of this worksheet is to be transferred from Excel into a specific Access table. How do I do this using VBA?

I cant seem to put the file in so I hope you guys understand! Thanks in advance for helping me!!

War es hilfreich?

Lösung

You can use ADO. First, set a reference to the ADO library in the VBE: Tools, References. Look for Microsoft ActiveX Date Objects Library 6.1 (or 6.0) and tick the box next to it.

Then you can use the code below to post data from a sheet to a table in the Access database (use this in a loop if you want to do multiple sheets):

Dim i As Long, j As Long
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim arr() As Variant

'Load the data from a sheet into an array
arr = Sheets(1).Range("A2:B10").Value

'Connect to Access database
Set cn = New ADODB.Connection

With cn
    .ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents\Database1.accdb"
    .Open
End With

'Post data to table
Set rs = New ADODB.Recordset

With rs
    .Source = "Table1"
    .ActiveConnection = cn
    .CursorType = adOpenStatic
    .CursorLocation = adUseServer
    .LockType = adLockOptimistic
    .Open

    For i = 1 To UBound(arr, 1)
        .AddNew

        For j = 1 To UBound(arr, 2)
            .Fields(j).Value = arr(i, j)    'This assumes you have an autonumber ID field. (Field indexes in recordsets are 0 based.)
        Next

        .Update
    Next

    .Close
End With

'Clean up
Set rs = Nothing
cn.Close
Set cn = Nothing

EDIT:

If you want to check if a record already exists in the table, use the recordset FILTER property. Say you have an "ID" in column 1 of your spreadsheet and an "ID" field in your database table, then do:

rs.Filter = "ID='" & arr(1,j) & "'"

If rs.RecordCount > 0 then
    'Record(s) already exist
...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top