考虑到我有一个Excel工作簿和Access表不一定具有相似的结构(即它们可能没有相同数量的列)。
当我打开工作簿时,Excel表格中的行将由Access表格中的行填充(从Access表格复制到使用宏指定的Excel工作表的特定单元格范围内)。
然后我修改Excel表格中的某些单元格。
我还在Excel工作表中有一个名为“保存”的按钮。按下时,这将执行一个宏。
我的问题:当点击“保存”按钮时,如何更新Access表以反映Excel表格中的更改?
答案 0 :(得分:6)
您可以使用ADO和一些代码。
以下是一些注释。
让我们说你得到一些类似的数据:
Sub GetMDB()
Dim cn As Object
Dim rs As Object
strFile = "C:\Docs\DBFrom.mdb"
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile & ";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
strSQL = "SELECT * FROM Table1"
rs.Open strSQL, cn
With Worksheets(7)
For i = 0 To rs.Fields.Count - 1
.Cells(1, i + 1) = rs.Fields(i).Name
Next
rs.MoveFirst
.Cells(2, 1).CopyFromRecordset rs
End With
End Sub
您可以使用ADO更新数据,如下所示:
Sub UpdateMDB()
Dim cn As Object
Dim rs As Object
''It wuld probably be better to use the proper name, but this is
''convenient for notes
strFile = Workbooks(1).FullName
''Note HDR=Yes, so you can use the names in the first row of the set
''to refer to columns
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
& ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open strCon
''Selecting the cell that are different
strSQL = "SELECT * FROM [Sheet7$] s " _
& "INNER JOIN [;Database=c:\Docs\DBFrom.mdb;].Table1 t " _
& "ON s.id=t.id " _
& "WHERE s.Field1<>t.Field1"
rs.Open strSQL, cn, 1, 3 ''adOpenKeyset, adLockOptimistic
''Just to see
''If Not rs.EOF Then MsgBox rs.GetString
''Editing one by one (slow)
rs.MoveFirst
Do While Not rs.EOF
rs.Fields("t.Field1") = rs.Fields("s.Field1")
rs.Update
rs.MoveNext
Loop
''Batch update (faster)
strSQL = "UPDATE [;Database=c:\Docs\DBFrom.mdb;].Table1 t " _
& "INNER JOIN [Sheet7$] s " _
& "ON s.id=t.id " _
& "SET t.Field1=s.Field1 " _
& "WHERE s.Field1<>t.Field1 "
cn.Execute strSQL
End Sub