简体   繁体   English

将数据从 excel 复制到使用 VBA 访问?

[英]Copying data from excel into access with VBA?

Im trying to update an Access database with new code to add to one aggregate list of scan entries.我正在尝试使用新代码更新 Access 数据库,以添加到一个扫描条目聚合列表中。 The macro needs to open the access file, copy the range from excel and paste it at the bottom of the database to add to the already existing records.宏需要打开访问文件,从excel中复制范围并将其粘贴到数据库底部以添加到现有记录中。 Then save the access .accdb file and then close.然后保存访问 .accdb 文件,然后关闭。 Any tips particularly on the copying and pasting data portion?特别是关于复制和粘贴数据部分的任何提示?

Use ACE.OLEDB .使用ACE.OLEDB Create an SQL INSERT STATEMENT.创建 SQL 插入语句。 Code would look something like below:代码如下所示:

    Sub Test()
        accessFilePath = "C:\someDB.accdb"
        Call ExecuteSQLCmd("INSERT INTO `" & accessFilePath & "`.`Table` (col1,col2,col3) SELECT col1,col2,col3 FROM [Sheet1$]", accessFilePath)
     End Sub

   Sub ExecuteSQLCmd(cmd As String, accessFilePath as String )

        Dim cnn As ADODB.Connection
        Dim sql As String

        Set cnn = New ADODB.Connection
        cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & accessFilePath & ";Persist Security Info=False;"

        If Not (cnn Is Nothing) Then
            'Execute Sql
            cnn.Execute (cmd)
            'Close
            cnn.Close
        End If
        Set cnn = Nothing
    End Sub

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

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