0

我有一个 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 
4

1 回答 1

0

这将检查是否存在不是0-9、az 或逗号的内容如果您想排除特定字符,那么.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
于 2012-09-07T17:06:29.817 回答