我正在尝试在 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 的建议创建指向 Excel 工作表的链接。在下面的示例中,我将链接命名为“tblExcelData”。然后“tblDestination”将根据您的要求为工作表行的每个“单元格”存储单独的记录。在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
关于excel - 用于与 Excel 交互的 MS Access VBA 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10999444/