Kyle Friesen via AccessMonster.com said:
Hello,
I have a form that I want to make a few fields required. If I set the
required property to Yes in the table the form is linked to, an error
message comes up when one tries to save the form. However, this does
not identify which fields are required for input. Is there a way to
communicate which field the user needs to update. For example Msgbox
"You must complete the Customer field".
I'd recommend a somewhat different approach from that suggested by Dave.
Rather than writing a BeforeUpdate event procedure for each control --
which won't work anyway unless the user actually modifies the control --
it would be a lot simpler to write a single BeforeUpdate event for the
form itself. In that procedure, check each required field to see if it
has been filled in, and accumulate a list of those that haven't been.
Then if that list is not empty, you can cancel the update and display an
error message that includes the list of fields to be fixed.
Here's a function you can paste into a standard module and call from the
form's BeforeUpdate event. It checks every text box, combo box, list
box, and check box on the form, but only if the control's Tag property
is set to "Required". That lets you designate, by tagging, those fields
that are required. The function is passed a reference to the form to be
checked and returns True if required fields are missing, as well as
displaying a message and setting the focus to the first control that is
required but empty.
'----- start of function code -----
Function fncRequiredFieldsMissing(frm As Form) As Boolean
Dim ctl As Access.Control
Dim strErrCtlName As String
Dim strErrorMessage As String
Dim lngErrCtlTabIndex As Long
Dim blnNoValue As Boolean
lngErrCtlTabIndex = 99999999 'more than max #controls
For Each ctl In frm.Controls
With ctl
Select Case .ControlType
Case acTextBox, acComboBox, acListBox, acCheckBox
If .Tag = "Required" Then
blnNoValue = False
If IsNull(.Value) Then
blnNoValue = True
Else
If .ControlType = acTextBox Then
If Len(.Value) = 0 Then
blnNoValue = True
End If
End If
End If
If blnNoValue Then
strErrorMessage = strErrorMessage & vbCr & _
" " & .Name
If .TabIndex < lngErrCtlTabIndex Then
strErrCtlName = .Name
lngErrCtlTabIndex = .TabIndex
End If
End If
End If
Case Else
' Ignore this control
End Select
End With
Next ctl
If Len(strErrorMessage) > 0 Then
MsgBox "The following fields are required:" & vbCr & _
strErrorMessage, _
vbInformation, "Required Fields Are Missing"
frm.Controls(strErrCtlName).SetFocus
fncRequiredFieldsMissing = True
Else
fncRequiredFieldsMissing = False
End If
End Function
'----- end of function code -----
To use the function, create a BeforeUpdate event for your form like
this:
'----- start of event procedure code -----
Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = fncRequiredFieldsMissing(Me)
End Sub
'----- end of event procedure code -----