I have some VBA code that takes field values from an excel worksheet and dumps them into a table in Access. I need to check if the record in the table exists first, and if it does than only update it. If it does not then add a new record. Here is the code I have so far.
Thanks in advance for any help.
KT
Code:
Sub UpdateMasterDb()
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim intResale As Integer
Dim intHours As Integer
On Error Resume Next
intHours = Worksheets("Project pricing summary").Range("G60").Value + Worksheets("Project pricing summary").Range("G61").Value _
+ Worksheets("Project pricing summary").Range("G62").Value
intResale = Worksheets("Project information").Range("D26").Value + Worksheets("Project information").Range("D28").Value
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
"Data Source=T:\Quot\CONTROLS\Formulas\Estworksheet\Master Quote List\Controls Estimating Database.mdb;"
Set rs = New ADODB.Recordset
rs.Open "Tbl_Controls_Quote_Master", cn, adOpenKeyset, adLockOptimistic, adCmdTable
rs.AddNew
rs.Fields("Project") = Worksheets("Project information").Range("L6").Value
rs.Fields("Customer") = Worksheets("Project information").Range("D6").Value
rs.Fields("Location") = Worksheets("Project information").Range("D7").Value
rs.Fields("Quote_Type") = Worksheets("Project information").Range("L7").Value
rs.Fields("Estimator") = Worksheets("Project information").Range("D8").Value
rs.Fields("Date_Quoted") = Worksheets("Project information").Range("L5").Value
rs.Fields("Comments_Scope") = Worksheets("Project pricing summary").Range("C15").Value
rs.Fields("File_Path_Hyperlink") = Application.ActiveWorkbook.Name & "#" & Application.ActiveWorkbook.FullName & "#"
rs.Fields("Resale") = intResale
rs.Fields("Hardware") = Worksheets("Project information").Range("D27").Value
rs.Fields("Eng_Hours") = intHours
rs.Fields("Travel") = Worksheets("Project pricing summary").Range("L59").Value
rs.Update
' If Err = -2147217887 Then
' MsgBox ("Unable to update database, record already exists!")
' Else
' MsgBox ("Database has been updated")
' End If
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
Worksheets("Project information").Range("B1").Value = "True"
End Sub
KT