You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Access表单必填字段校验VBA代码改为公共子程序

Access表单必填字段校验公共VBA子程序实现方案

1. 创建标准模块并编写公共校验子程序

打开Access的VBA编辑器(按Alt+F11),插入一个标准模块(不要选类模块),粘贴以下代码:

Public Sub CheckRequiredFields(ByRef frm As Form, ByRef Cancel As Integer)
    Dim msg As String, Style As Integer, Title As String
    Dim nl As String, ctl As Control

    nl = vbNewLine & vbNewLine

    For Each ctl In frm.Controls
        If ctl.ControlType = acTextBox Then
            If ctl.Tag = "*" And Trim(ctl & "") = "" Then
                msg = "Data Required for '" & ctl.Name & "' field!" & nl & _
                      "You can't save this record until this data is provided!" & nl & _
                      "Enter the data and try again . . . "
                Style = vbCritical + vbOKOnly
                Title = "Required Data..."
                MsgBox msg, Style, Title
                ctl.SetFocus
                Cancel = True
                Exit For
            End If
        End If
    Next
End Sub

2. 在目标表单的BeforeUpdate事件中调用公共子程序

打开需要启用校验的表单设计视图,打开其VBA代码窗口,找到Form_BeforeUpdate事件(无则手动创建),添加调用代码:

Private Sub Form_BeforeUpdate(Cancel As Integer)
    CheckRequiredFields Me, Cancel
End Sub

关键修改说明

  • 原代码中的Me(当前表单对象)替换为传入的frm参数——标准模块无法直接访问表单的Me对象,必须通过参数传递表单实例。
  • Cancel参数用ByRef传递,确保公共子程序中对Cancel的修改能同步到表单事件,实现阻止保存的效果。
  • 保留原校验逻辑:仅检查Tag属性为*的文本框,为空时弹出提示、聚焦控件并阻止记录保存。

内容的提问来源于stack exchange,提问作者Nashid Iftekhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:15:39