VBA初始单元更改无法触发功能-后续更改成功触发功能-正则表达式单元验证

时间:2018-07-27 16:11:39

标签: regex excel vba excel-vba

以下代码应防止任何人输入非数字字符。

Private Sub Worksheet_Change(ByVal Target As Range)

Static X As Variant
Dim rng2 As Range
Dim rng3 As Range

If IsEmpty(X) Then X = [a1:a10].Value2

Set rng2 = Intersect([a1:a10], Target)
If rng2 Is Nothing Then Exit Sub

Application.EnableEvents = False
For Each rng3 In rng2
    If Not isValidRegex(rng3, "\d+") Then rng3.Value = X(rng3.Row, 1)
Next
Application.EnableEvents = True

X = [a1:a10].Value2

End Sub

Function isValidRegex(rng As Range, pattern As String) As Boolean
Dim re As Object
Set re = CreateObject("vbscript.regexp")
re.pattern = pattern
isValidRegex = re.Test(rng.Value)
End Function

问题是在用户将A1:A10范围中的单元格更改为非数字字符,isValidRegex函数无法触发时第一次尝试...或者至少我认为是问题所在。也许与变量X有关。

我希望始终使用正则表达式模式...

1 个答案:

答案 0 :(得分:1)

也许以下代码对您有用

Private Sub Worksheet_Change(ByVal Target As Range)

Dim rng2 As Range
Dim rng3 As Range

    Set rng2 = Intersect([a1:a10], Target)
    If rng2 Is Nothing Then Exit Sub

    Application.EnableEvents = False
    For Each rng3 In rng2
        If Not isValidRegex(rng3, "\d+") Then Application.Undo
    Next
    Application.EnableEvents = True

End Sub