excel - 用于与 Excel 交互的 MS Access VBA 脚本

标签 excel ms-access vba

我正在尝试在 Microsoft Access 中编写一个 VBA 脚本,该脚本将与 Excel 工作表交互,循环遍历行,然后遍历行中的单元格,然后将信息拉回到 Access 表中。

这是一些 sudo 代码-

For Each Row
    For Each Cell in the Row
        Read the Cell
        Create a new Record in the Access table with the info from the cell
    End For Each
End For Each

您可以在下图中看到最终结果的简化示例。

我们拥有什么-

enter image description here

需要什么-

enter image description here

我以前编写过代码,但从未使用过 VBA;所以任何帮助将不胜感激!感谢您的帮助!!!

最佳答案

首先按照 @Remou 的建议创建指向 Excel 工作表的链接。在下面的示例中,我将链接命名为“tblExcelData”。然后“tblDestination”将根据您的要求为工作表行的每个“单元格”存储单独的记录。在tblDestination中,Seq#是长整型,Field NameField Value都是文本。

Public Sub foo20120612a()
    Dim db As DAO.Database
    Dim rsSrc As DAO.Recordset
    Dim rsDest As DAO.Recordset
    Dim fld As DAO.Field

    Set db = CurrentDb
    Set rsSrc = db.OpenRecordset("tblExcelData", dbOpenSnapshot)
    Set rsDest = db.OpenRecordset("tblDestination", _
        dbOpenTable, dbAppendOnly)
    Do While Not rsSrc.EOF
        For Each fld In rsSrc.Fields
            If fld.Name <> "Seq#" Then
                With rsDest
                    .AddNew
                    ![Seq#] = CLng(rsSrc![Seq#])
                    ![Field Name] = fld.Name
                    ![Field Value] = fld.value
                    .Update
                End With
            End If
        Next fld
        rsSrc.MoveNext
    Loop
    rsDest.Close
    Set rsDest = Nothing
    rsSrc.Close
    Set rsSrc = Nothing
    Set db = Nothing
End Sub

关于excel - 用于与 Excel 交互的 MS Access VBA 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10999444/

相关文章:

excel - 如果单元格在vba中有小数点,有没有办法引用?

vba - 将文件创建日期添加到列表中

vba - 在一个表中搜索值的数量,调整另一个表中的行数

vba - 如果工作表存在,则运行 sub。如果没有,显示消息并退出子

excel - 使用 Excel 构建插入语句

c# - .Net 程序集注册和依赖问题

forms - 如何让 Access 显示用户必须与之交互的子窗体?

java - [Microsoft][ODBC 驱动程序管理器] 游标状态无效

vba - 保存并转到新记录后如何重置表单的格式

r - 检查R中是否存在数据表