3

我正在尝试在 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 中编码过;所以任何帮助将不胜感激!谢谢你的帮助!!!

4

2 回答 2

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

您可以通过删除字段和列名称中的空格和保留字来使生活更轻松。

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

于 2012-06-12T15:09:42.150 回答
2

首先按照@Remou 的建议创建一个指向您的 Excel 工作表的链接。在以下示例中,我将链接命名为“tblExcelData”。然后“tblDestination”将按照您的要求为工作表行的每个“单元格”存储单独的记录。In 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
于 2012-06-12T16:07:01.513 回答