VBA 字母和数字互换,Cells和Range转换

这里给两个写好的函数

1.数字转为字母,输入数字即可转化为列号(这里最大到ZZ,注意传入要大写),比如:NumToLetter(28)="AB"

Function NumToLetter(num As Long) As String
Dim alphabet()
'a-z字母表
alphabet() = 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")
'判断列,字母拆分
If num <= 26 Then
    NumToLetter = alphabet(num - 1)
ElseIf num <= 729 Then
    NumToLetter = alphabet((num \ 26) - 1) & alphabet((num Mod 26) - 1)
End If
End Function

2.字母转为数字,输入列号即可转化为数字,比如:LetterToNum(AB)=28

Function LetterToNum(Letter As String) As Long
Dim alphabet As Variant
Dim i, num, num1, num2, num3 As Integer
Dim Letter1, Letter2, Letter3 As String
'a-z字母表
alphabet = 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")
If Len(Letter) = 1 Then
    For i = 0 To UBound(alphabet)
        If Letter = alphabet(i) Then
            num = i + 1
        End If
        LetterToNum = num
    Next
ElseIf Len(Letter) = 2 Then
    Letter1 = Left(Letter, 1)
    Letter2 = Right(Letter, 1)
    For i = 0 To UBound(alphabet)
        If Letter1 = alphabet(i) Then
            num1 = i + 1
        End If
    Next
    For i = 0 To UBound(alphabet)
        If Letter2 = alphabet(i) Then
            num2 = i + 1
        End If
    Next
    num = num1 * 26 + num2
    LetterToNum = num
ElseIf Len(Letter) = 3 Then
    Letter1 = Left(Letter, 1)
    Letter2 = Mid(Letter, 2, 1)
    Letter3 = Right(Letter, 1)
        Letter1 = Left(Letter, 1)
    Letter2 = Right(Letter, 1)
    For i = 0 To UBound(alphabet)
        If Letter1 = alphabet(i) Then
            num1 = i + 1
        End If
    Next
    For i = 0 To UBound(alphabet)
        If Letter2 = alphabet(i) Then
            num2 = i + 1
        End If
    Next
    For i = 0 To UBound(alphabet)
        If Letter3 = alphabet(i) Then
            num3 = i + 1
        End If
    Next
    num = num1 * 26 * 26 + num2 * 26 + num3
    LetterToNum = num
Else
    MsgBox "输入不正确"
End If
End Function

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今夕乃何夕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值