Access Code - mantantory fields in a form

。_饼干妹妹 提交于 2019-12-24 19:18:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!