仅限细胞内容验证

问题描述 投票:1回答:1

我喜欢在Non pritables,回车,空格和不想要的符号上验证单元格内容。在我的代码中使用此if语句:

If CellChck.Text Like "*[^-_,A-Z-0-9]*" Then

它几乎是完美的唯一缺点是没有捕获4个符号:*()@

谁能给我正确的代码?

这是我的代码:

Dim RangeToCheck As Range
Dim CellChck As Range

For Each CellCheck In RangeToCheck
If Len(CellCheck.Text) > 0 Then
If CellCheck.Text Like "*[^-_,A-Z-0-9]*" Then   
CellCheck.Font.Color = vbRed
CellCheck.Font.Bold = True        
Else:   CellCheck.Font.Color = vbBlack
CellCheck.Font.Bold = False
End If
End If
Next CellCheck
excel-vba vba excel
1个回答
0
投票

我建议创建自定义函数来验证,而不是使用Like运算符:

Function ContainsSpecialChar(stringToProcess As String) As Boolean

ContainsSpecialChar = False
Dim specialChars As Variant: specialChars = Array("^", "_", " ", ")", "(", "*", "@", _
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", _
"0", "1", "2", "3", "4", "5", "6", "7", "8", "9")

For Each char In specialChars
    If InStr(1, stringToProcess, char) > 0 Then
        ContainsSpecialChar = True
        Exit Function
    End If
Next char

End Function

在你的If条件下你可以写:If ContainsSpecialChar(CellCheck.Text) Then

© www.soinside.com 2019 - 2024. All rights reserved.