简体   繁体   中英

MS-Access forms: Search for a record using combo box, and either update record if a match is found, or begin to add new record if no match

I currently have a table with three fields.

ID2: Number (also my primary key), Field1: shorttext, Field2: shorttext

I am trying to create a form where all three fields are displayed, and when I enter a value into ID2, the matching record is displayed. However, if there are no matches, I would like it to create a new record with the new value.

I am working off this question: MS Access search for record by textbox instead of dropdown

However, I cannot seem to replicate the results. My current code is:

Private Sub ID2_AfterUpdate()
    Dim rs As DAO.Recordset
    Set rs = Me.RecordsetClone
    rs.FindFirst "[ID2]=" & ID2
    If rs.NoMatch Then
        MsgBox "Sorry, no such record '" & ID2 & "' was found.", _
               vbOKOnly + vbInformation
    Else
        Me.Recordset.Bookmark = rs.Bookmark
    End If
    rs.Close
End Sub

I used the auto-create form button from the "Create" tab, and added the above code to the ID2 textbox with "Build event, code builder". I understand I am not using the rs.FindFirst function properly. I would like to ask:

  1. What I am doing wrong in the above code
  2. What to change the rs.NoMatch part to so it goes to add a new record if there is no match. (ideally it would clear the other fields)

Thankyou for any help, I am new to access and any help would be greatly appreciated.

Controls used to enter search criteria should be UNBOUND.

Consider:

...
    rs.FindFirst "[ID2]=" & Me.ID2
    If rs.NoMatch Then
        MsgBox "Sorry, no such record '" & Me.ID2 & "' was found.", _
               vbOKOnly + vbInformation
        DoCmd.GoToRecord , , acNewRec
        Me.ID2 = Null
    Else
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM