[英]Updating Access Database from Excel Worksheet Data
I extract data from my Access database into an Excel worksheet using a macro. 我使用宏将Access数据库中的数据提取到Excel工作表中。 I first open a connection to the database, define my sql statement in a string var and then dump that data in a recordset:
我首先打开与数据库的连接,在字符串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
This works perfectly. 这很完美。 I distribute this to some people and ask them to update fields.
我将其分发给某些人,并要求他们更新字段。 I then need to update the Access data with data that is passed back.
然后,我需要使用传回的数据更新Access数据。 The simple thing in terms of design is that the extracted excel data mirrors the access db in structure so the update query should be simple.
就设计而言,简单的事情是提取的excel数据在结构上镜像了访问数据库,因此更新查询应该很简单。 Also there is a primary key, so I would just need to map on that field.
还有一个主键,所以我只需要映射该字段即可。
Any ideas how this can be done? 任何想法如何做到这一点? Can I load the whole excel datasheet into a recordset and run some snazzy update query?
我可以将整个Excel数据表加载到记录集中并运行一些时髦的更新查询吗?
You need to loop over rows on sheet 1, and for each row make sql string that looks like: 您需要循环遍历工作表1上的行,并为每一行制作sql字符串,如下所示:
"update [Master table] set
TableField1 = " & Range(Row, Col1).Value & ","
TableField2 = " & Range(Row, Col2).Value & ","
...
where IDTableField = " & Range(Row, IDColNum).Value
and then do 然后做
db.Execute thatString
PS: There are may be mistakes in my syntax. PS:我的语法可能有误。 And you need to convert cell values to strings when making string.
并且在创建字符串时需要将单元格值转换为字符串。
An extension of shibormot's solution using DAO: 使用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
Threw in the chr(34) for string data 放入chr(34)以获取字符串数据
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.