PDA

View Full Version : How to replace Access data from EXCEL instead of adding to it?



truzilla
07-09-2008, 12:12 PM
Hi all,

So I created this macro below that essentially imports data from an excel spreadsheet to a specified table within an access database. I based it off of another one I found online.

Currently, I need a change that will replace the existing access data in the table instead of adding to it, which it currently does. Any help would be greatly appreciated!! Thanks! :clap:


Sub WORKINGIMPORTER()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim cn As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=C:\Documents and Settings\Test dB.mdb"
' open a recordset
Set rs = New ADODB.Recordset
rs.Open "HFM", cn, adOpenKeyset, adLockOptimistic, adCmdTable
' all records in a table
r = 3 ' the start row in the worksheet
Do While Len(Range("A" & r).Formula) > 0
' repeat until first empty cell in column A
With rs
.AddNew ' create a new record
' add values to each field in the record
.Fields("Date") = Range("A" & r).Value
.Fields("Region") = Range("B" & r).Value
.Fields("ABC") = Range("C" & r).Value
.Fields("Revenue") = Range("D" & r).Value
.Update ' stores the new record
End With
r = r + 1 ' next row
Loop
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub

akanchu
07-10-2008, 06:50 PM
To update the data, you will have to first retrieve the record using some key. So your rs.open "HFM".. will change to rs.open "select ...... where keyfield = value to search"

then once the record is retrieved, do not use rs.addnew
just assign values and use .update

Hope this helps.

Bob Phillips
07-11-2008, 01:44 AM
I do believe that you can do an update without the preliminary read if you know the item exists.