我使用宏将Access数据库中的数据提取到Excel工作表中。我首先打开与数据库的连接,在字符串var中定义我的sql语句,然后将该数据转储到记录集中:
Dim db As Database
Dim rs As RecordSet
Dim sql As String
Dim dbLocation As String
dbLocation = ThisWorkbook.Path & "\database\data.accdb"
Set db = OpenDatabase(dbLocation)
sql = "Select * FROM [Master Table]"
Set rs = db.OpenRecordSet(sql, dbOpenSnapshot)
If Not rs.EOF Then
Worksheets("Sheet1").Range("A1").CopyFromRecordset rs
End If
rs.Close
Set rs = Nothing
db.Close
Set db = Nothing
这完美无缺。我将此分发给某些人并要求他们更新字段。然后,我需要使用传回的数据更新Access数据。在设计方面,简单的事情是提取的excel数据在结构中镜像访问db,因此更新查询应该很简单。还有一个主键,所以我只需要在该字段上进行映射。
有什么想法可以做到这一点?我可以将整个Excel数据表加载到记录集中并运行一些时髦的更新查询吗?
答案 0 :(得分:2)
您需要在表单1上循环遍历行,并且对于每一行,使sql字符串看起来像:
"update [Master table] set
TableField1 = " & Range(Row, Col1).Value & ","
TableField2 = " & Range(Row, Col2).Value & ","
...
where IDTableField = " & Range(Row, IDColNum).Value
然后再做
db.Execute thatString
PS:我的语法可能有错误。并且在制作字符串时需要将单元格值转换为字符串。
答案 1 :(得分:0)
使用DAO扩展shibormot的解决方案:
Set objConnection = CreateObject("DAO.DBEngine.36")
Set db = objConnection.OpenDatabase(strDBPath, blnExclusive, blnReadOnly, strPassword)
For Each row In Range("A1:C3").Cells
strSQL = "UPDATE table SET "
strSQL = strSQL & "Field1 = " & Chr(34) & row.Cells(1) & Chr(34) & ","
strSQL = strSQL & "Field2 = " & Chr(34) & row.Cells(2) & Chr(34) & ","
strSQL = strSQL & "Field3 = " & Chr(34) & row.Cells(3) & Chr(34)
Db.Execute
Next
在chr(34)中输入字符串数据