【问题标题】:Access Code - mantantory fields in a form访问代码 - 表单中的必填字段
【发布时间】:2017-05-08 21:51:41
【问题描述】:

我在表单中使用了以下 vba 代码。

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 

我的问题是表单包含不能留空的文本框。例如,如果 Surname 和 Name 字段必须有一个值,并且用户只填写 Surname 并按下 imgCustomer_Click,那么数据库将继续运行而不会显示错误以填充空字段。有什么想法吗?

ps:我可以使用 vba 来自动用值填充字段吗?

【问题讨论】:

  • 您正在将表单保存到数据库中。如果您将数据库中的字段定义为 NOT NULL,那么数据库将不允许这些字段保持为空,并且会在保存时报错 DoCmd.Close
  • 正如保罗所说,可以根据需要在表中设置字段,然后让Access nag用户进行输入。如果您需要自定义消息,请使用 BeforeUpdate 事件表单中的 VBA 代码进行验证。作为旁注,请注意 acSaveYes 参数与保存记录无关,它用于保存表单设计更改。当 1. 关闭表/查询/表单,或 2. 移动到另一条记录,或 3. 运行代码 DoCmd.RunCommand acCmdSaveRecord 时,记录被保存。

标签: vba ms-access


【解决方案1】:

您可以编写一个函数来验证必填字段,并在验证成功后继续。

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

然后你可以在你的过程中调用它:

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

编辑:

如果是绑定表单,则需要取消自动更新,验证成功后才保存记录。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多