简体   繁体   English

使用ADO 5工作表转移到5个表中

[英]Transferring using ADO 5 worksheets into 5 tables

I have been struggling to transfer data from multiple excel worksheets into multiple access tables. 我一直在努力将数据从多个Excel工作表传输到多个访问表中。 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. 我有5个工作表,每个工作表都将从Excel转移到特定的Access表中。 How do I do this using VBA? 如何使用VBA做到这一点?

I cant seem to put the file in so I hope you guys understand! 我似乎无法把文件放进去,所以希望你们能理解! Thanks in advance for helping me!! 在此先感谢您对我的帮助!

You can use ADO. 您可以使用ADO。 First, set a reference to the ADO library in the VBE: Tools, References. 首先,在VBE:工具,参考中设置对ADO库的参考。 Look for Microsoft ActiveX Date Objects Library 6.1 (or 6.0) and tick the box next to it. 查找Microsoft ActiveX日期对象库6.1(或6.0),然后选中它旁边的框。

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): 然后,您可以使用下面的代码将工作表中的数据发布到Access数据库中的表中(如果要处理多个工作表,请在循环中使用此代码):

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. 如果要检查表中是否已存在记录,请使用记录集FILTER属性。 Say you have an "ID" in column 1 of your spreadsheet and an "ID" field in your database table, then do: 假设您在电子表格的第1列中有一个“ ID”,在数据库表中有一个“ ID”字段,然后执行以下操作:

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

If rs.RecordCount > 0 then
    'Record(s) already exist
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM