首页 > 解决方案 > 用于数据验证的 VBA

问题描述

最近在一本书上发现了一个数据验证的代码,就是:

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Address = “$A$1” Then
    If Not IsNumeric(Target) Then
    MsgBox “Enter a number in cell A1.”
    Range(“A1”).ClearContents
    Range(“A1”).Activate
    End If
  End If
End Sub

我想更改它以验证我在 A 列中的自定义格式,即 XY 和 6 号(XY123456)并修改了代码。但是MsgBox会不断弹出,格式错误时无法关闭。有人可以给我一些建议。谢谢

Private Sub Worksheet_Change(ByVal Target As Range)
  If Target.Column = 1 Then
    If Left(Target.Value, 2) <> "XY" Or 
       Not IsNumeric(Right(Target.Value,6)) Or 
       Len(Target.Value) <> 8  Then
    MsgBox “Wrong Format”
    Target.ClearContents
    Target.Activate
    End If
  End If
End Sub

标签: vbaexcel

解决方案


将您的代码更改为

Private Sub Worksheet_Change(ByVal Target As Range)

    On Error GoTo EH

    If Target.Column = 1 Then
        If Left(Target.Value, 2) <> "XY" Or Not IsNumeric(Right(Target.Value, 6)) Or Len(Target.Value) <> 8 Then
            Application.EnableEvents = False
            MsgBox "Wrong Format"
            Target.ClearContents
            Target.Activate
        End If
    End If

EH:
    Application.EnableEvents = True

End Sub

您需要关闭事件,否则Target.ClearContents将一次又一次地触发事件,直到您用完堆栈空间。为了使它更加防弹,我还添加了一个错误处理程序,以确保在发生错误时再次打开事件处理程序。


推荐阅读