Many times we need to determine if a particular character, whether alone, or among other characters in a String, is an AlphaNumeric character (if it falls in the range of characters from A - Z, or a to z, or 0 - 9). The traditional method of doing this in VBA is to compare the Asc(UCase(character)) to the ANSI values for the ranges. The Windows API, however, provides a Function designed specifically for this purpose IsCharAlphaNumeric(). IsCharAlphaNumeric() is significantly faster than its counterpart. You simply pass the ASCII value of the character as an Argument to this Function and it returns True if the character is AlphaNumeric and False if it is not. Both the slow and faster versions of the code will be illustrated below. Be sure to Declare the API Function(s) in the Declarations Section of a Module.
- Slow version of the code:
- strTestChar As String, intTestChar As Integer
-
Const conFirstChar = 65
-
Const conLastChar = 90
-
Const conFirstDigit = 48
-
Const conLastDigit = 57
-
-
strTestChar = "4"
-
intTestChar = Asc(UCase(strTestChar))
-
-
If (intTestChar >= conFirstChar And intTestChar <= conLastChar) Or _
-
(intTestChar >= conFirstDigit And intTestChar <= conLastDigit) Then
-
'the character is AlphaNumeric
-
Else
-
'the character is Not AlphaNumeric
-
End If
- Faster and more efficient version of the code:
- Private Declare Function IsCharAlphaNumeric Lib "User32" Alias "IsCharAlphaNumericA" (ByVal cChar As Byte) As Long
-
Private Declare Function IsCharAlpha Lib "User32" Alias "IsCharAlphaA" (ByVal cChar As Byte) As Long
- IsCharAlphaNumeric(Asc(strTestChar)) Then
-
'the character is AlphaNumeric
-
Else
-
'the character is Not AlphaNumeric
-
End If
-
-
'Similiar Function to test for Alphas
-
If IsCharAlpha(Asc(strTestChar)) Then
-
'the character is an Alpha
-
Else
-
'the character is Not an Alpha
-
End If
- NOTE: There is also a similar API Function (IsCharAlpha()) that checks a character to see whether itis an Alpha (a - z or A - Z). Its code and Declaration is also listed.