MS Access VBA脚本与Excel接口
我正在尝试在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的build议创build一个到Excel工作表的链接。 在下面的例子中,我将链接命名为“tblExcelData”。 然后,“tblDestination”将根据您的要求为工作表行的每个“单元格”存储单独的logging。 在tblDestination
, Seq#
是长整型, Field Name
和Field 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
我build议您使用DoCmd的各种向导或TransferSpreadsheet方法链接Excel工作表,并使用链接的Excel表格简单地运行操作查询。
联合查询是必需的。 让我们打电话给你的链接电子表格。
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
通过删除字段和列名中的空格和保留字,可以使生活更轻松。
列出使用星号(*)的字段通常最好如上所示。