Using a combobox to check if record exist then populate form

Anonymous
2014-09-10T22:04:07+00:00

So I have posted my question to several forums and have had some good response but no resolution. I am quite new to Access 2010 and VBA. So here is my issue. I have built a Navigation Page with several forms(bound) so my users can enter data and saved to a table. What I have is a room delay form to capture information for a  medical procedure and to document when a delay occurs. My TABLE is tblDelay and my form is FormDelay.

On occasion my users will enter some information and save and close the form. Then will need to edit the record. I have attempted to create a Assession Num Search in the form header based on someone's recommendation using this code:

Private Sub cboAssessionSearch_AfterUpdate()

Const MESSAGETEXT = "This Assession Number already exists."

 If Not IsNull(DLookup("AssessionNumber", "tblDelay", "AssessionNumber=" & Me.AssessionNumber)) Then

 MsgBox MESSAGETEXT, vbExclamation, "Invalid Operation"

 'code to filter form for the existing record

 Me.Filter = "AssessionNumber=" & Me.AssessionNumber

 Me.FilterOn = True

 Else

 'code to move to new record row

 DoCmd.GoToRecord , , acNewRec

 End If

End Sub

I can find the populated Assession Numbers in the combobox but I need to have certain criteria. If the assession number exists the populate the form with the record fields so an edit can be made and an update to the record made in the table. If the Assession Number does not exist leave the form blank so a new record can be entered. Nothing happens when I select a Assession Number and hit enter. No error message indication record exists or not.

I have built several buttons (Add, Edit, Delate, Clear, and Close) in the header. If a assession Numbers need edited and updated then repopulate the form with the appropriate record found using the Assession Num Search combobox, If no record found, the enter new information.

Table Field Names

dept, Rm_Num, MRN, AssessionNumber, CaseNumber (Not inclusive of all fields, If I can get these filed to populate I can get the rest)

Form Names

cboDept, cboRmNum, txtMRN, txtAssessionNumber, txtCaseNumber (Not inclusive of all boxes)

Bound Form to table

Any help finding resolution would be of GREAT HELP!!! 

Thank you in advance,

Kerry

Microsoft 365 and Office | Access | For home | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

51 answers

Sort by: Most helpful
  1. Anonymous
    2014-09-12T20:58:07+00:00

    1.  By synchronize here all that's meant is that the unbound combo box will always show the contact represented by the form's current record.  This doesn't really have anything to do with finding a contact, and if omitted the form would still function in that respect.  It's just an added refinement which means that if the user navigates to a contact by means other than the combo box, e.g. by the built in navigation buttons or by means of the keyboard, the combo box will always show the current contact, and therefore not confuse the user by showing a previously selected contact, which could be the case without this code: Me.cboGotoContact = Me.ContactID

    2.  First it checks that the control has a value with: If Not IsNull(ctrl) Then

    i.e. that the user has not simply deleted whatever was selected in the control.  If they have done this then none of the following code is executed and nothing happens.  Otherwise if the value of the control is zero, which, by virtue of SELECT 0, "<New Contact>" in the UNION query, means that <New Contact> has been selected, it moves the form to an empty new record.

    If a value other than zero has been selected, i.e. a contact, finds the row in an exact copy of the form's recordset, returned by the form's RecordsetClone property.  It then assigns the RecordsetClone's Bookmark property to the form's Bookmark property, which has the effect of moving the form to the record which was found in the RecordsetClone, i.e. the selected contact.

    So, as Scott surmised, in the combo box's AfterUpdate event procedure it's the RecordsetClone property which 'identifies the table' by virtue of its returning an exact copy of the form's recordset.  The code does not need to know what table or query this is, the fact that it's working with an exact copy of the form's recordset is sufficient.

    In the control's NotInList event procedure it doesn't need to know anything about the recordset at all.  This code executes if the user types in a new value not in the list.  The new value is passed into the procedure as the NewData argument, and, after user confirmation via a message box, the form is then moved to an empty new record and the value typed into the combo box is inserted into the new record.  My demo is a little more complex in this respect than you'd need because the name typed in is actually the concatenated values for two separate fields, FirstName and LastName, so has to be parsed into its constituent values.  If we assume that in my demo the value was only a single field, LastName, it would be analogous to yours as you are concerned with just the one field, and the code would be simplified as follows:

    Private Sub cboGotoContact_NotInList(NewData As String, Response As Integer)

        Dim ctrl As Control

        Dim strMessage As String

        Set ctrl = Me.ActiveControl

        strMessage = "Add " & NewData & " to list?"

        'if user confirms insert, move form to new record

        ' and insert value into last name control

        If MsgBox(strMessage, vbYesNo + vbQuestion) = vbYes Then

            Response = acDataErrContinue

            ctrl.Undo

            DoCmd.GoToRecord acForm, Me.Name, acNewRec

            Me.LastName = NewData

        Else

            Response = acDataErrContinue

            ctrl.Undo

        End If

    End Sub

    Was this answer helpful?

    0 comments No comments
  2. Anonymous
    2014-09-12T19:25:54+00:00

    So if I am going to try this code, I can change name to AssessionNumber to check if it exists. If it does populate form with recordsetclone. This should populate my form for editing. If AssessionNumber doesnot exist then add record. I will try to conver this to my form and see where it goes.

    KA

    Was this answer helpful?

    0 comments No comments
  3. ScottGem 68,840 Reputation points Volunteer Moderator
    2014-09-12T18:03:34+00:00

    I do not understand how table is identified to synchronize name. Where is table identified?

    How does this and the next VB Sub cboGoToContact_NotInList identify table and fields to populate new record.

    KA

    Not Ken, but I can answer those questions. The table is identified by the Recordsource of the form. As soon as you assign a Recordsource to the form, you shouldn't need anything else. I"m not 100% sure but I suspect Ken's code uses the Form's RecordsetClone property to move the record pointer based on the value selected in the combobox. If you are using unbound forms, then all bets are off and you have to write code to populate the controls. But it doesn't sound like you are doing that.

    Was this answer helpful?

    0 comments No comments
  4. Anonymous
    2014-09-12T17:53:42+00:00

    Thank you for your recommendations and assistance. I have reviewed your FindContact dB and attempting to understand its flow and use of VB. Please bear in mind I am fairly new to Access development and coding using VB. I would first of all try to explain your code back to you to see if I am on tract.

    VB Code from frmFindContact

     1. Opening the form fires Sub Form_Current and synchronizes the contact combo box Me.cboGoToContact (Form combo box) = Me.ContactID (table field). If the contact is listed in Me.cboGoToContact then

    1. Sub cboGoToContact_AfterUpdate() fires and if Me.ActiveControl which should be Me.cboGoToContact focus then Me.RecordsetClone fires in Else clause otherwise new record and move focus to input name.

    I do not understand how table is identified to synchronize name. Where is table identified?

    How does this and the next VB Sub cboGoToContact_NotInList identify table and fields to populate new record.

    Lets first start with this and let me digest it until I understand. I would like to try and convert this to my form and tables.

    Thanks for your patients.

    KA

    Was this answer helpful?

    0 comments No comments
  5. Anonymous
    2014-09-11T21:36:18+00:00

    1.  How do I get the MessageText "No Matching Record" and "Warning" to fire? Can't seem to see that message with data input.

    2.   Also, Is it possible to leave the form blank until a Go To Contact has been selected.

    1.   Can we add a message for edit/update to ask if user really wants to change the data in a record.

    1.   That's really only in there as a backstop.  Normally that message will never be displayed, only in the unlikely circumstance that the combo box lists more distinct values than are actually represented in the form's recordset.  If a user enters a new value then the form's NotInList event procedure (q.v.) will execute and prompt the user for confirmation of whether they wish to add the new item to the list or not.  If they confirm then the form is moved to a new record, and the new value assigned to the control (actually two controls in my case as the name is parsed, but it would be one in yours).

    2.  You could move to an empty new record when the form opens by putting this in its Open event procedure:

            DoCmd.GoToRecord acForm, Me.Name, acNewRec

    3.  the simple way is to put the following in the form's BeforeUpdate event procedure:

        Const MESSAGETEXT = "Do you wish to save the changes to the record?"

        If MsgBox(MESSAGETEXT, vbQuestion + vbYesNo, "Confirm") = vbNo Then

            Cancel = True

            Me.Undo

        End If

    However, the fact that a record is updated does not per se mean the values of its data have been changed.  The above also is clumsy if the user attempts to save the record by closing the form.  For a solution which only prompts for confirmation only where the data has actually changed see the ChangedRecordDemo file in my same OneDrive folder.  The code for the form's module in this case is rather more complex, as follows:

    Option Compare Database

    Option Explicit

    Private Sub Form_BeforeInsert(Cancel As Integer)

        Me.DateTimeStamp = Now()

    End Sub

    Private Sub Form_BeforeUpdate(Cancel As Integer)

     On Error GoTo Err_Handler

        Const MESSAGETEXT = "Data has changed.  Save record?"

        If Not Me.NewRecord Then

            ' store unsaved values of bound controls in array

            StoreProposedVals Me

            ' if data in controls has changed get user

            ' confirmation to save record

            If RecordWillChange() Then

                If MsgBox(MESSAGETEXT, vbQuestion + vbYesNo, "Confirm") = vbNo Then

                    Cancel = True

                    Me.Undo

                End If

            End If

        Else

            If MsgBox("Save new record", vbQuestion + vbYesNo, "Confirm") = vbNo Then

                Cancel = True

                Me.Undo

            Else

                ' timestamp record

                Me.DateTimeStamp = Now()

                Me.UpdatedBy = GetUser()

            End If

        End If

    Exit_Here:

       Exit Sub

    Err_Handler:

       MsgBox Err.Description, vbExclamation, "Error"

       Resume Exit_Here

    End Sub

    Private Sub Form_Current()

        On Error GoTo Err_Handler

        If Not Me.NewRecord Then

            ' store current values of bound controls in array

            StoreCurVals Me

        End If

    Exit_Here:

        Exit Sub

    Err_Handler:

        MsgBox Err.Description, vbExclamation, "Error"

        Resume Exit_Here

    End Sub

    Private Sub Form_Error(DataErr As Integer, Response As Integer)

        Const IS_DIRTY = 2169

        ' suppress system error message if form

        ' is closed while record is unsaved,

        ' NB: changes to current record will be lost

        If DataErr = IS_DIRTY Then

             Response = acDataErrContinue

        End If

    End Sub

    The above code calls the following function to determine if the data in the record will in fact be changed if the record is saved:

    Public Function RecordWillChange() As Boolean

       Dim n As Integer, intlast As Integer

       Dim var As Variant

       Dim aOld(), aNew()

       intlast = UBound(aOldVals) - 1

       ' loop through array of original values

       ' and store in new array

       ReDim Preserve aOld(UBound(aOldVals))

       For Each var In aOldVals()

           aOld(n) = var

           n = n + 1

       Next var

       n = 0

       ' loop through array of edited values

       ' and store in new array

       ReDim Preserve aNew(UBound(aOld))

       For Each var In aNewVals()

           aNew(n) = var

           ' if any value has changed then return True

           If (IsNull(aNew(n)) And Not IsNull(aOld(n))) _

               Or (Not IsNull(aNew(n)) And IsNull(aOld(n))) _

               Or aNew(n) <> aOld(n) Then

               RecordWillChange = True

               Exit For

           End If

           n = n + 1

       Next var

    End Function

    Was this answer helpful?

    0 comments No comments