Best way to write data to a table using data from a form

SteveL13
SteveL13 used Ask the Experts™
on
I'm trying to figure out what is the best way (VBA code) to write data to a table that is not the record source of a form using a command button.  But if the record already exists, then overwrite the data.

For example:

Form field -= txtFirstName to be written to the unbound table to a field named FirstName
Form field -= txtLastName to be written to the unbound table to a field named LastName

etc.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
omgangIT Manager

Commented:
Are you determining record existence strictly by First Name & Last Name?  Meaning, is there only one record for John Smith?  Can there be two?

Your steps will be
1) Does a record exist in the destination table for [FirstName] = txtFirstName AND [LastName] = txtLastName.  You can use a DLookup function, a DAO RecordSet Find method in VBA, etc.

2) If True/Yes, run and update query:  UPDATE MyTable SET Address = txtAddress, City = txtCity, State = txtState, Zip = txtZip, Phone = txtPhone WHERE [FirstName] = txtFirstName AND [LastName] = txtLastName
3) if False/No, run an insert query:  INSERT INTO MyTable FirstName, LastName, Address, City, State, Zip, Phone VALUES (txtFirstName, txtLastName, txtAddress, etc.)

OM Gang

Author

Commented:
The existence of a previous record would be a RecordID.

What would the code look like for step 1?
omgangIT Manager

Commented:
<<The existence of a previous record would be a RecordID.>>

That makes it a bit trickier.  If your user is entering data into a form you won't have a RecordID to query with.  Unless that form is bound, in some way, to the destination table (which it isn't as stated in your original Q).

But, to the point.

Dim rs As DAO Recordset

Set rs = CurrentDb.OpenRecordset("TheDeistinationTable")
rs.FindFirst "[LastName] = '" & txtLastName & "' AND [FirstName] = '" & txtFirstName & "'"
If not rs.NoMatch Then
     'update query or VBA code to update the recordset record (might as well since you're here)
Else
     'insert query or VBA code to insert a new record into the recordset
End If

Set rs = Nothing


OM Gang
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Distinguished Expert 2017

Commented:
If you are duplicating data, you might consider normalizing your schema so you don't have to write the same data into multiple tables.

In some cases, you can use a query with a left join that would allow you to add data to two related tables at once so you would simply need to populate the name field twice.  Once in table1 and again in table2.

The AfterUpdate event of LastName
Me.DuplicateLastName = Me.LastName
omgangIT Manager

Commented:
I tested this this morning.
I created a table (MyTable) with RecordID, LastName, FirstName, Address, etc.
I created an unbound form (MyForm) with txtLastName, txtFirstName, txtAddress, etc.
I added a command button (cmdUpdate) to the form.  Here's the code for the button.  This works as you want, i.e. it identifies if the a record exists or not.

OM Gang

Option Compare Database
Option Explicit

Private Sub cmdUpdate_Click()
On Error GoTo Err_cmdUpdate_Click

    Dim rs As DAO.Recordset
    Dim strFind As String, strMsg As String

    Set rs = CurrentDb.OpenRecordset("MyTable", dbOpenDynaset)
    
    strFind = "[LastName] = '" & Me.txtLastName & "' AND [FirstName] = '" & Me.txtFirstName & "'"

    rs.FindFirst strFind
    If Not rs.NoMatch Then
        strMsg = "Record exists for " & Me.txtLastName & ", " & Me.txtFirstName & ".  RecordID = " & rs("RecordID")
    Else
        strMsg = "Record does not exist for " & Me.txtLastName & ", " & Me.txtFirstName
    End If
    
    MsgBox strMsg, vbOKOnly, "Person Exists?"

Exit_cmdUpdate_Click:
    'destroy object variable
    Set rs = Nothing
    Exit Sub
    
Err_cmdUpdate_Click:
    MsgBox Err.Number & ", " & Err.Description, vbCritical, "Error in cmdUpdate procedure"
    Resume Exit_cmdUpdate_Click

End Sub

Open in new window

IT Manager
Commented:
I've updated the code to include UPDATE and INSERT functionality as appropriate.
OM Gang

Option Compare Database
Option Explicit

Private Sub cmdUpdate_Click()
On Error GoTo Err_cmdUpdate_Click

    Dim rs As DAO.Recordset
    Dim strFind As String, strMsg As String

    Set rs = CurrentDb.OpenRecordset("MyTable", dbOpenDynaset)
    
    strFind = "[LastName] = '" & Me.txtLastName & "' AND [FirstName] = '" & Me.txtFirstName & "'"

    rs.FindFirst strFind
    If Not rs.NoMatch Then
        'record exists so we'll update
        rs.Edit
            'only update address fields
            rs("Address") = Me.txtAddress
            rs("City") = Me.txtCity
            rs("State") = Me.txtState
            rs("Zip") = Me.txtZip
        rs.Update
    
        strMsg = "Record exists for " & Me.txtLastName & ", " & Me.txtFirstName & ".  RecordID = " & rs("RecordID") & " has been updated."
    Else
        'record does not exist so lets we'll create a new one
        rs.AddNew
            rs("LastName") = Me.txtLastName
            rs("FirstName") = Me.txtFirstName
            rs("Address") = Me.txtAddress
            rs("City") = Me.txtCity
            rs("State") = Me.txtState
            rs("Zip") = Me.txtZip
        rs.Update
        
        'get id value from newly created record
        rs.FindFirst strFind
    
        strMsg = "Record does not exist for " & Me.txtLastName & ", " & Me.txtFirstName & ".  A new record has been added.  RecordID = " & rs("RecordID")
    End If
    
    MsgBox strMsg, vbOKOnly, "Person Exists?"

Exit_cmdUpdate_Click:
    'destroy object variable
    Set rs = Nothing
    Exit Sub
    
Err_cmdUpdate_Click:
    MsgBox Err.Number & ", " & Err.Description, vbCritical, "Error in cmdUpdate procedure"
    Resume Exit_cmdUpdate_Click

End Sub

Open in new window

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial