I have the following code to add data to a an access table. The code works fine. Now i would like to modify this code to perform the following:
Loop through each row of data and see if the ID # already exists somewhere in the access table. if it does, update that record with the new data. If it doesn't exist, create a new record with the new data. then move on to the next row and perform the same.
Any help would really be appreciated.
Here's the code that works.
Sub AccessRecord()
Dim nc As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set nc = New ADODB.Connection
nc.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & "Data Source = \\S11ECFF\Project\db1.mdb;"
Set rs = New ADODB.Recordset
rs.Open "T1_Header", nc, adOpenKeyset, adLockOptimistic, adCmdTable
Sheets("HData").Select
Mycount = Worksheets("HData").Range("B1").CurrentRegion.Rows.Count
r = 1
For r = 1 To Mycount
If Cells(r, 2).Value <> Empty Then
With rs
.AddNew
.Fields("ID") = Range("A" & r).Value
.Fields("Case_No") = Range("B" & r).Value
.Fields("File_No") = Range("C" & r).Value
.Update
End With
End If
Next r
rs.Close
Set rs = Nothing
nc.Close
Set nc = Nothing
End Sub
Loop through each row of data and see if the ID # already exists somewhere in the access table. if it does, update that record with the new data. If it doesn't exist, create a new record with the new data. then move on to the next row and perform the same.
Any help would really be appreciated.
Here's the code that works.
Sub AccessRecord()
Dim nc As ADODB.Connection, rs As ADODB.Recordset, r As Long
' connect to the Access database
Set nc = New ADODB.Connection
nc.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & "Data Source = \\S11ECFF\Project\db1.mdb;"
Set rs = New ADODB.Recordset
rs.Open "T1_Header", nc, adOpenKeyset, adLockOptimistic, adCmdTable
Sheets("HData").Select
Mycount = Worksheets("HData").Range("B1").CurrentRegion.Rows.Count
r = 1
For r = 1 To Mycount
If Cells(r, 2).Value <> Empty Then
With rs
.AddNew
.Fields("ID") = Range("A" & r).Value
.Fields("Case_No") = Range("B" & r).Value
.Fields("File_No") = Range("C" & r).Value
.Update
End With
End If
Next r
rs.Close
Set rs = Nothing
nc.Close
Set nc = Nothing
End Sub