使用IsCharAlphaNumeric()而不是ASCII值

很多时候,我们需要确定某个特定字符(无论是单独的字符还是字符串中的其他字符)是否为AlphaNumeric字符(如果它属于从A-Z或a到z或0-9的字符范围) 。 在VBA中执行此操作的传统方法是将Asc(UCase(character))与范围的ANSI值进行比较。 但是,Windows API提供了专门为此目的设计的函数IsCharAlphaNumeric()。 IsCharAlphaNumeric()的速度明显快于其对应的速度。 您只需将字符的ASCII值作为参数传递给此函数,如果字符是AlphaNumeric,则返回True,否则返回False。 下面将说明慢速和快速版本的代码。 确保在模块的声明部分声明API函数。

  1. 慢速版本的代码:

     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
  2. 更快,更高效的代码版本:

     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
  3. 注意:还有一个类似的API函数(IsCharAlpha()),用于检查字符以查看是否是Alpha(a-z或A-Z)。 还列出了其代码和声明。

From: https://bytes.com/topic/access/insights/663682-use-ischaralphanumeric-rather-than-ascii-values

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值