问题
I am using the following vba code in my form.
Private Sub imgCustomer_Click()
On Error GoTo Err_Handler
DoCmd.Close acForm, "frmCustomer", acSaveYes
DoCmd.OpenForm "frmSplashScreen"
Exit_This_Sub:
Exit Sub
Err_Handler:
MsgBox "Error #: " & Err.Number & " " & Err.Description
Resume Exit_This_Sub
End Sub
My problem is that the form contains textbox which must not left empty. If for example Surname and Name fields must have a value and the user only fill the Surname and press the imgCustomer_Click, the database will continue without showing a error to fill up the empty fields. Any ideas?
ps: Can I use a vba so it will automatically fill the field with a value, instead?
回答1:
You can write a function to validate the required fields and proceed when validation is successful.
Private Function FormValidated() As Boolean
With Me
If IsNull(.FirstControlName.Value) Then Exit Function
If IsNull(.SecondControlName.Value) Then Exit Function
'additional controls...
End With
FormValidated = True
End Function
You can then call it in your procedure:
Private Sub imgCustomer_Click()
On Error GoTo Err_Handler
If Not FormValidated Then
MsgBox "Validation failed.", vbExclamation
GoTo Exit_This_Sub
End If
DoCmd.Close acForm, "frmCustomer", acSaveYes
DoCmd.OpenForm "frmSplashScreen"
Exit_This_Sub:
Exit Sub
Err_Handler:
MsgBox "Error #: " & Err.Number & " " & Err.Description
Resume Exit_This_Sub
End Sub
Edit:
If this is a bound form, you need to cancel the auto-update and save the record only when validation is successful.
Option Explicit
'Set a flag for manual update
Private mIsUserUpdate As Boolean 'Flag
'Cancel auto-update
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Not mIsUserUpdate Then Cancel = True
End Sub
'Save
Private Sub imgCustomer_Click()
On Error GoTo Err_Handler
If Not FormValidated Then
MsgBox "Validation failed.", vbExclamation
GoTo Exit_This_Sub
End If
mIsUserUpdate = True 'flag ON
DoCmd.RunCommand acCmdSaveRecord
DoCmd.Close acForm, "frmCustomer", acSaveYes
DoCmd.OpenForm "frmSplashScreen"
Exit_This_Sub:
mIsUserUpdate = False 'Flag OFF
Exit Sub
Err_Handler:
MsgBox "Error #: " & Err.Number & " " & Err.Description
Resume Exit_This_Sub
End Sub
'Validation
Private Function FormValidated() As Boolean
With Me
If IsNull(.FirstControlName.Value) Then Exit Function
If IsNull(.SecondControlName.Value) Then Exit Function
'additional controls...
End With
FormValidated = True
End Function
来源:https://stackoverflow.com/questions/43831524/access-code-mantantory-fields-in-a-form