Search code examples
vbacheckboxtextbox

Access VBA not working when already executed previously


I'm pretty new at VBA. I have a form with a text box and a check box. If I open the form and click the check box without populating the text box, I get a message box to enter comments.

However, in the same session, if I unchecked the box and recheck it, I do not get the message box to enter comments even tho the text box is blank.

How can I get the code to "refire" in the same session to give me the message box to enter comments?

Below is my code:

Private Sub Check29_Click()

    If IsNull(Me.Text16) Then

        MsgBox "Comments are Required.", vbCritical
        Me.Check29 = Null
        Exit Sub

    Else

        If Me.Check29 = -1 Then

            Dim RS As DAO.Recordset
            Set RS = CurrentDb.OpenRecordset("Exclusions", dbOpenDynaset)
            RS.AddNew
            RS("HW535ID") = Me![HWID]
            RS("Excluded") = "Yes"
            RS("BOA Assignee") = Me![AssignedBA]
            RS("Comments") = Me![Text16]
            RS("CheckBox") = Me![Check29]
            RS("Date of Exclusion") = Me![Text115]
            RS("ReviewID") = Me![Text33]
            RS.Update
            RS.Close
            Set RS = Nothing
            Exit Sub

        Else

            DoCmd.SetWarnings False
            DoCmd.OpenQuery ("RemoveExclusion")
            Me.Text16 = Null
            Exit Sub

        End If

    End If

End Sub

Solution

  • I can see a logic problem in the code. Please be aware that this line:

      Me.Check29 = Null
    

    will re-trigger the _click event and produce unexpected results. And it is also incorrect (should be Me.Check29.Value=False). Please try the revised version below:

    Declare a module level variable

     Option Explicit
     Private bCancel as Boolean
    

    The event code (I also made more corrections):

    Private Sub Check29_Click()
    
    if bCancel Then Exit Sub
    bCancel = False
    
    If Trim(Me.Text16.Text) = vbnullstring Then
    
        MsgBox "Comments are Required.", vbCritical
        bCancel = True
        Me.Check29.Value = False
        bCancel =  False
        Exit Sub
    
    Else
    
        If Me.Check29.Value = True Then
    
            Dim RS As DAO.Recordset
            Set RS = CurrentDb.OpenRecordset("Exclusions", dbOpenDynaset)
            RS.AddNew
            RS("HW535ID") = Me![HWID]
            RS("Excluded") = "Yes"
            RS("BOA Assignee") = Me![AssignedBA]
            RS("Comments") = Me![Text16]
            RS("CheckBox") = Me![Check29]
            RS("Date of Exclusion") = Me![Text115]
            RS("ReviewID") = Me![Text33]
            RS.Update
            RS.Close
            Set RS = Nothing
            Exit Sub
    
        Else
    
            DoCmd.SetWarnings False
            DoCmd.OpenQuery ("RemoveExclusion")
            Me.Text16.Text = vbnullstring
            Exit Sub
    
        End If
    
    End If
    
    End Sub