如何使用VBA禁用Excel中每个单元格中的特定键

时间:2012-09-07 06:00:43

标签: excel vba

我有一张excel表,用户将在每个单元格中输入元数据。我需要做的是编写一个只允许使用字母数字字符和逗号的宏。

我为测试目的编写了一个宏,它不允许使用特殊字符。但是在我在单元格中输入一个有效字符后,它允许我不允许使用的字符。我不知道如何纠正它。

我的代码:

Private Sub WorkBook_Open()
       MsgBox "Running the Disable_Keys() Macro"
       Call ThisWorkbook.Disable_Keys
End Sub

Sub MyMsg()
    MsgBox "Press Another Key"
End Sub

Sub Disable_Keys()

     Dim I As Long
     Dim KeysArray As Variant
     Dim Key As Variant

     KeysArray = Array("@", "!", "~", "#", "$", "&", "|", "\", ":", "*", "_", "-", "=", "'", ";", "<", ">", "?", "/", "'", ":")

     For Each Key In KeysArray
          Application.OnKey Key, "ThisWorkbook.MyMSg"
     Next Key
  End Sub 

1 个答案:

答案 0 :(得分:0)

这将检查是否存在 0-9,a-z或逗号的内容 如果要排除特定字符,则.Pattern将是您更改的内容 如果找到了什么,那么单元格无效,它将清除单元格。

Private Sub Worksheet_Change(ByVal Target As Range)

Dim TestCell
Dim RE As Object
Dim REMatches As Object

Set RE = CreateObject("vbscript.regexp")
With RE
    .MultiLine = False
    .Global = False
    .IgnoreCase = True
    .Pattern = "[^0-9A-Z,]"
End With

For Each TestCell In Target.Cells
    Set REMatches = RE.Execute(TestCell.Value)
    If REMatches.Count > 0 Then
        MsgBox "Invalid:" & TestCell.Address & "-" & TestCell.Value
        TestCell.Value = ""
    End If
Next

End Sub