【问题标题】:MS Access VBA script to interface with ExcelMS Access VBA 脚本与 Excel 交互
【发布时间】:2012-06-12 15:06:27
【问题描述】:

我正在尝试在 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

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

我们有什么-

需要什么-

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

【问题讨论】:

  • 请阅读Remou wrote,已经有一个内置的方法可以做到这一点。即使将范围读入数组而不是循环遍历每个单元格也会更好。

标签: excel ms-access vba


【解决方案1】:

首先按照@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

【讨论】:

    【解决方案2】:

    我建议您使用各种向导或 DoCmd 的 TransferSpreadsheet 方法链接 Excel 工作表,然后使用链接的 Excel 表格运行操作查询。

    联合查询是必需的。让我们将您的链接电子表格称为 t。

    SELECT * INTO Table1
    FROM (
        SELECT [Seq#], "Name" As [Field Name], [Name] As [Field Value]
        FROM t
        UNION ALL
        SELECT [Seq#], "Location" As [Field Name], [Location] As [Field Value]
        FROM t
        UNION ALL
        SELECT [Seq#], "Car" As [Field Name], [Car] As [Field Value]
        FROM t ) imp
    
    INSERT INTO Table1
    SELECT * FROM (
        SELECT [Seq#], "Name" As [Field Name], [Name] As [Field Value]
        FROM t
        UNION ALL
        SELECT [Seq#], "Location" As [Field Name], [Location] As [Field Value]
        FROM t
        UNION ALL
        SELECT [Seq#], "Car" As [Field Name], [Car] As [Field Value]
        FROM t ) imp
    

    去掉字段名和列名中的空格和保留字可以让生活更轻松。

    通常最好列出要使用星号 (*) 的字段,如上所示。

    【讨论】:

    • 我使用向导从 Excel 中提取数据,效果很好。但是,我以前从未使用过操作查询来组织数据。你能详细说明一下如何使用动作查询来按照图片显示的方式格式化数据吗?
    猜你喜欢
    • 2017-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 1970-01-01
    • 2015-10-27
    • 1970-01-01
    • 2020-10-29
    相关资源
    最近更新 更多