很多时候,我们需要确定某个特定字符(无论是单独的字符还是字符串中的其他字符)是否为AlphaNumeric字符(如果它属于从A-Z或a到z或0-9的字符范围) 。 在VBA中执行此操作的传统方法是将Asc(UCase(character))与范围的ANSI值进行比较。 但是,Windows API提供了专门为此目的设计的函数IsCharAlphaNumeric()。 IsCharAlphaNumeric()的速度明显快于其对应的速度。 您只需将字符的ASCII值作为参数传递给此函数,如果字符是AlphaNumeric,则返回True,否则返回False。 下面将说明慢速和快速版本的代码。 确保在模块的声明部分声明API函数。
- 慢速版本的代码:
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
- 更快,更高效的代码版本:
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
- 注意:还有一个类似的API函数(IsCharAlpha()),用于检查字符以查看是否是Alpha(a-z或A-Z)。 还列出了其代码和声明。
From: https://bytes.com/topic/access/insights/663682-use-ischaralphanumeric-rather-than-ascii-values