I can\'t get my code to add new records and update existing records in the table I have. I have two tables; one temporary table (tblTempData) and another table (tblCommon).
An alternative approach.
Try to break down your code by creating a helper function for each task, Exists()
, Add()
and Update()
. It will be easier to read and maintain the code.
Option Explicit
Private rsCommon As DAO.Recordset
Public Sub UpdateExistingRecords()
On Error GoTo ErrTrap
Dim rs As DAO.Recordset
Set rs = CurrentDb().OpenRecordset("SELECT * FROM tblTempData", dbOpenSnapshot)
Set rsCommon = CurrentDb().OpenRecordset("SELECT * FROM tblCommon", dbOpenDynaset)
Dim idx As Long
For idx = 1 To rs.RecordCount
If ExistsInCommon(rs![Item ID]) Then
If Not Update(rs) Then
MsgBox "Failed to update.", vbExclamation
GoTo Leave
End If
Else
If Not Add(rs) Then
MsgBox "Failed to add.", vbExclamation
GoTo Leave
End If
End If
rs.MoveNext
Next
Leave:
If Not rs Is Nothing Then rs.Close
If Not rsCommon Is Nothing Then rsCommon.Close
Set rs = Nothing
Set rsCommon = Nothing
Exit Sub
ErrTrap:
MsgBox Err.Description, vbCritical
Resume Leave
End Sub
' Exists - 'Assumes Id is String
Private Function ExistsInCommon(ByVal Id As String)
ExistsInCommon = DCount("*", "tblCommon", "[Item ID] = '" & Id & "'") > 0
End Function
' Update
Private Function Update(rs As DAO.Recordset) As Boolean
With rsCommon
.FindFirst "[Item ID] = '" & rs![Item ID] & "'"
If .NoMatch Then Exit Function
.Edit
![Item Description] = rs![Item Description]
![Material Number] = rs![Material Number]
![User] = rs![User]
![Supplier] = rs![Supplier]
![Current Status] = rs![Current Status]
![Remarks] = rs![Remarks]
.Update
.MoveFirst
End With
Update = True
End Function
'Add
Private Function Add(rs As DAO.Recordset) As Boolean
With rsCommon
.AddNew
![Item Description] = rs![Item Description]
![Material Number] = rs![Material Number]
![User] = rs![User]
![Supplier] = rs![Supplier]
![Current Status] = rs![Current Status]
![Remarks] = rs![Remarks]
![Item ID] = rs![Item ID]
.Update
End With
Add = True
End Function