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

如何在MS Access宏中测试自定义函数返回结果并显示提示信息?

英国邮编验证VBA函数的结果判断实现

我编写了一个用于验证英国邮编格式的VBA函数IsUKPostCode,它会根据输入情况返回三种结果:

  • "Valid":邮编格式有效
  • "No Post Code entered":未输入任何邮编内容
  • 空值:邮编格式无效

目前我已在MS Access宏中通过语句 RunCode IsUKPostCode([Forms]![People maintenance]![People.Post Code]) 调用该函数,现在需要编写正确的判断逻辑,在邮编格式无效或未输入时显示对应的提示信息。

原函数代码

Public Function IsUKPostCode(strInput As String)
'
' 使用正则表达式验证邮编格式
'
Dim RgExp As Object
Set RgExp = CreateObject("VBScript.RegExp")
'
' 初始化函数返回值
'
IsUKPostCode = ""
'
' 检查是否有输入值
'
If strInput = "" Then
  IsUKPostCode = "No Post Code entered"
  Exit Function
End If
'
' 验证英国邮编的正则表达式
RgExp.Pattern = "^[A-Z]{1,2}\d{1,2}[A-Z]?\s\d[A-Z]{2}$"
'
' 匹配检查
'
If RgExp.Test(strInput) = True Then
  IsUKPostCode = "Valid"
End If
End Function

实现结果判断的代码方案

方案1:在表单事件中使用VBA判断(推荐)

在表单的BeforeUpdate事件中添加以下代码,可在用户保存数据前自动验证邮编:

Private Sub Form_BeforeUpdate(Cancel As Integer)
    Dim postCodeResult As String
    postCodeResult = IsUKPostCode(Me![Post Code]) ' 用Me引用当前表单控件更简洁

    Select Case postCodeResult
        Case "Valid"
            ' 格式有效,允许继续操作
        Case "No Post Code entered"
            MsgBox "请输入邮编信息。", vbInformation, "提示"
            Cancel = True ' 阻止表单保存
            Me![Post Code].SetFocus ' 光标定位到邮编输入框
        Case ""
            MsgBox "邮编格式无效,请输入正确的英国邮编。", vbCritical, "错误"
            Cancel = True ' 阻止表单保存
            Me![Post Code].SetFocus
    End Select
End Sub

方案2:使用If语句直接判断

如果是在独立的VBA过程中调用函数,可使用以下If逻辑:

Sub CheckPostCode()
    Dim result As String
    result = IsUKPostCode([Forms]![People maintenance]![People.Post Code])

    If result = "" Then
        MsgBox "邮编格式不正确,请检查后重新输入。", vbExclamation
        [Forms]![People maintenance]![People.Post Code].SetFocus
        Exit Sub
    ElseIf result = "No Post Code entered" Then
        MsgBox "请填写邮编内容。", vbInformation
        [Forms]![People maintenance]![People.Post Code].SetFocus
        Exit Sub
    End If
    ' 邮编有效时执行后续操作
End Sub

方案3:在Access宏中设置条件判断

如果要在宏中实现判断,可添加以下步骤:

  1. 添加条件:IsUKPostCode([Forms]![People maintenance]![People.Post Code]) = ""
    • 执行MsgBox操作,设置提示文本为"邮编格式无效,请输入正确的英国邮编。",类型为"关键消息"
    • 执行CancelEvent操作,阻止后续流程
  2. 添加条件:IsUKPostCode([Forms]![People maintenance]![People.Post Code]) = "No Post Code entered"
    • 执行MsgBox操作,设置提示文本为"请输入邮编信息。",类型为"信息"
    • 执行CancelEvent操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 10:05:12