是否可以在 Excel 中使用 VBA 将 Excel 数据附加到 Access 数据库文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23661746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 03:08:44  来源:igfitidea点击:

Is it possible to append Excel data to an Access database file using VBA within Excel?

excelvbaexcel-vbaaccess-vba

提问by user3637835

I have three cells in an in Excel 2010 worksheet, say a1, a2, and a3. Every time the user runs my Excel macro, I need it to take the info in those cells and append it to an existing Access DB file. That is all that will be in the db file, just a running list.

我在 Excel 2010 工作表中有三个单元格,比如 a1、a2 和 a3。每次用户运行我的 Excel 宏时,我都需要它获取这些单元格中的信息并将其附加到现有的 Access DB 文件中。这就是 db 文件中的全部内容,只是一个运行列表。

So, I don't want to IMPORT from Access. I want this all to happen on the Excel side, preferably without opening access at all. Is this possible or can I just tell my husband to forget about it?

所以,我不想从 Access 导入。我希望这一切都发生在 Excel 端,最好根本不开放访问。这是可能的还是我可以告诉我丈夫忘记它?

If it IS possible, can someone give me a clue as to how to go about it? Or where to learn about it? I'm ok with VBA in Excel but have zero experience with Access or even with databases.

如果可能的话,有人能给我一个关于如何去做的线索吗?或者去哪里学习?我对 Excel 中的 VBA 没问题,但对 Access 甚至数据库的经验为零。

Thanks!

谢谢!

回答by MikeD

Create a reference to the Microsoft DAO 3.6 object libraryand start playing with this code:

创建对Microsoft DAO 3.6 对象库的引用并开始使用以下代码:

Sub DBInsert()
Dim DB As DAO.Database
Dim RS As DAO.Recordset

    ' open database
    Set DB = DAO.OpenDatabase("C:\Users\Myself\Desktop\MyDB.mdb")

    ' open table as a recordset
    Set RS = DB.OpenRecordset("Table1")

    ' add a record to the recordset
    RS.AddNew

    ' fill fields with data ... in this case from cell A1
    RS.Fields("Field1") = [A1]

    ' write back recordset to database
    RS.Update

    ' important! cleanup
    RS.Close

    ' forget to close the DB will leave the LDB lock file on the disk
    DB.Close

    Set RS = Nothing
    Set DB = Nothing
End Sub

Create a button on the sheet and place this code inside the Button_Click() so the user can send the data to your DB when all entry is done.

在工作表上创建一个按钮并将此代码放在 Button_Click() 中,以便用户可以在完成所有输入后将数据发送到您的数据库。

Further resources:

更多资源:

Office 2013 / Data Access / How do I ...

Office 2013 / 数据访问 / 我如何...

Choosing ADO or DAO for Working with Access Databases

选择 ADO 或 DAO 来使用 Access 数据库