前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >VBA: 字母转为数字

VBA: 字母转为数字

作者头像
Exploring
发布2022-09-20 14:50:52
2.3K0
发布2022-09-20 14:50:52
举报
文章被收录于专栏:数据处理与编程实践

文章背景:在工作中,有时需要将字母转为数字字符串,比如将A转为00001B转为00002。下面通过VBA编写将字母(A~XFD)转为数字的函数。

代码语言:javascript
复制
Function LetterToNum(ByVal letter As String) As String
    
    'Convert letter(A-XDF) to numerical string, like A to 00001, B to 00002 ...
    
    Dim temp As String, number As Integer
    
    If IsAlpha(letter) Then
    
        'Capital letter
        temp = UCase(letter)
    
        'First letter
        number = Asc(Left(temp, 1)) - Asc("A") + 1
        
        'Second letter
        If Len(letter) >= 2 Then
        
            number = number * 26 + Asc(Mid(temp, 2, 1)) - Asc("A") + 1
            
            'Third letter
            If Len(letter) >= 3 Then
            
                number = number * 26 + Asc(Mid(temp, 3, 1)) - Asc("A") + 1
                
                If Len(letter) >= 4 Then
                
                    LetterToNum = "Letter more than three"
                    
                    Exit Function
                    
                End If
            
            End If
            
        End If
        
        LetterToNum = Format(number, "00000")
            
    '非字符串
    Else
    
        LetterToNum = "Not a string"
    
    End If
    
    Exit Function
    
End Function

Private Function IsAlpha(s As String) As Boolean

    'Check if a string only contains letters

    IsAlpha = Len(s) And Not s Like "*[!a-zA-Z]*"
    
End Function

(1)上述函数实现的功能是将字母(A to XFD)转化为相应的数值型字符串,比如将A转为00001B转为00002

(2)Asc函数:Returns an Integer representing the character code corresponding to the first letter in a string.

参考资料:

[1] vba 字母列转为数字列(https://zhidao.baidu.com/question/624292971619231564.html?qbpn=2_2&tx=&word=vba%20%E5%AD%97%E6%AF%8D%E5%88%97%E8%BD%AC%E4%B8%BA%E6%95%B0%E5%AD%97%E5%88%97&fr=newsearchlist)

[2] excel vba判断字符串是否只包含字母(https://www.learnfk.com/code-examples/vb/excel-vba-check-if-a-string-only-contains-letters.html)

[3] Asc function(https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/asc-function)

[4] Format function(https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/format-function-visual-basic-for-applications)

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-08-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 数据处理与编程实践 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档