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
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