0
每個月我都要從大約30個excel文件更新我的MS Access數據庫。它們具有完全相同的結構和格式。我嘗試多次修改此代碼以更新數據庫中的每個表,但我沒有成功。 (在這個論壇發現)如何從多個Excel文件更新MS Access中的多個表?
我有3個問題: 怎麼可以說的VBA代碼來看看這個範圍在Excel模板中對應於MS Access數據庫中的這列?
如何讓這個vba代碼基於主鍵更新所有表中的一次?
然後,是否可以選擇所有這些excel文件所在的文件夾,並且代碼將遍歷所有文件?
Public Sub UpdatePriceList()
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim sProduct As String, sVariety As String, cPrice As Variant
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.ACE.OLEDB.12.0; " & _
"Data Source=C:\Users\Gord\Desktop\Database1.accdb;"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "PriceList", cn, adOpenKeyset, adLockOptimistic, adCmdTable
Range("A2").Activate ' row 1 contains column headings
Do While Not IsEmpty(ActiveCell)
sProduct = ActiveCell.Value
sVariety = ActiveCell.Offset(0, 1).Value
cPrice = ActiveCell.Offset(0, 2).Value
rs.Filter = "product='" & sProduct & "' AND variety='" & sVariety & "'"
If rs.EOF Then
Debug.Print "No existing record - adding new..."
rs.Filter = ""
rs.AddNew
rs("product").Value = sProduct
rs("variety").Value = sVariety
Else
Debug.Print "Existing record found..."
End If
rs("price").Value = cPrice
rs.Update
Debug.Print "...record update complete."
ActiveCell.Offset(1, 0).Activate ' next cell down
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
謝謝你提前!
我覺得這個問題會在計算器上更好 - 它似乎更多的編程比數據庫本身。投票結束。 –