首页 > 解决方案 > 正则表达式不触发 VBA

问题描述

这是我的正则表达式:

    Dim vbRegX As Object, vbRegXMatch As Object
    Set vbRegX = CreateObject("vbscript.regexp")

    With vbRegX
        .Global = True
        .IgnoreCase = True
        .Pattern = "^[a-zA-Z0-9_-]{1,20}$"
    End With

使用它的代码:

    Set vbRegXMatch = vbRegX.Execute(Me.txtProduct.Text)
    If vbRegXMatch.Count = 1 Then
        MsgBox "This string has invalid characters in it. Illegal characters are out side of the following ranges:" & vbNewLine & vbNewling & "a-z or A-Z" & vbNewLine & vbNewling & "0-9, - or _. Please try again."
        Cancel = True
        Me.txtProduct.SetFocus
        Set vbRegXMatch = Nothing
        Set vbRegX = Nothing
        Exit Sub
    End If

此代码使用无效字符触发,但长度大于 20 时不会触发。这是 Regex Buddy 给我的输出:

Dim FoundMatch As Boolean
Dim myRegExp As RegExp
Set myRegExp = New RegExp
myRegExp.Pattern = "^[a-zA-Z0-9_-]{1,20}$"
FoundMatch = myRegExp.Test(SubjectString)

谁能这么好心地指出我错过了什么?

控件的视觉效果:

在此处输入图像描述

标签: regexvbams-accessregexbuddy

解决方案


您的正则表达式匹配有效输入。因此,您需要.Test(your_string)并且如果结果是False,则需要触发错误。

代替

Set vbRegXMatch = vbRegX.Execute(Me.txtProduct.Text)
If vbRegXMatch.Count = 1 Then

If vbRegX.Test("1234555") = False Then

此外,由于您期望单场比赛,请使用

.Global = False

推荐阅读