Search code examples
ms-accessvbams-access-2016

MS Access VBA, efficient way to enable a button only after all required textboxes contains valid data


My code is working, but I just want to know if there is a more efficient way to achieve the same effect.

I have this layout in a form:

Form Layout

In my effort to foolproof the record creation process, I would like to have the "Save and Clear fields" button enabled only after all but the 'Comment' textbox/combobox contains some valid data.

The text/combo boxes are called txtBatteryID, cmbModelNumber, cmbChemistryType, txtSpecVoltage, txtSpecCapacity.

My code is as follow

Private Sub EnableSaveBtnCheck()
'this checks if the required fields contains valid data, if so, enables the save button.
    If Me.btnSaveAndCLear.Enabled = False Then
        If IsNull(txtBatteryID) = False And IsNull(cmbModelNumber) = False And IsNull(cmbChemistryType) = False And IsNull(txtSpecVoltage) = False And IsNull(txtSpecCapacity) = False Then
            Me.btnSaveAndCLear.Enabled = True
        End If
    End If
End Sub

As you can see, I did the most straightforward way of using AND to combine all must-have conditions in an IF statement. This sub is called in After_Update() event of each text/combo box. Like this:

Private Sub cmbChemistryType_AfterUpdate()
    Call EnableSaveBtnCheck
End Sub

My question, in the end, is: Is there a more efficient way to setup the condition "all text/combo box need to have something valid in them"? And is there a more elaborate way to check if the condition is met (something like a event on the form itself)?


Solution

  • Add the values of those 5 fields. If any of them is Null, the sum will be Null. So you only need call IsNull() once.

    If IsNull(txtBatteryID + cmbModelNumber + cmbChemistryType + txtSpecVoltage + txtSpecCapacity) = False Then