在 VBA 中将数字转换为字母数字

Converting a Number to Alphanumeric in VBA

我将下面的代码用作更大代码的一部分,将数字转换为其字母数字相等,即 1=A、2=B 等。虽然这确实有效,但它是疯狂的长代码,我是肯定有更好的方法来做到这一点,希望你们能提供帮助。

Sub Convert()

Time = Range("A1")

If Time = 1 Then
    E = "A"
Else
If Time = 2 Then
    E = "B"
Else
If Time = 3 Then
    E = "C"
Else
If Time = 4 Then
    E = "D"
Else
If Time = 5 Then
    E = "E"
Else
If Time = 6 Then
    E = "F"
Else
If Time = 7 Then
    E = "G"
Else
If Time = 8 Then
    E = "H"
Else
If Time = 9 Then
    E = "I"
Else
If Time = 10 Then
    E = "J"
Else
If Time = 11 Then
    E = "K"
Else
If Time = 12 Then
    E = "L"
Else
If Time = 13 Then
    E = "M"
Else
If Time = 14 Then
    E = "N"
Else
If Time = 15 Then
    E = "O"
Else
If Time = 16 Then
    E = "P"
Else
If Time = 17 Then
    E = "Q"
Else
If Time = 18 Then
    E = "R"
Else
If Time = 19 Then
    E = "S"
Else
If Time = 20 Then
    E = "T"
Else
If Time = 21 Then
    E = "U"
Else
If Time = 22 Then
    E = "V"
Else
If Time = 23 Then
    E = "W"
Else
If Time = 24 Then
    E = "X"
Else
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If

MsgBox E



End Sub

这是一种方式。

Sub numberToLetter()

    Dim Time As Integer
    Dim E As String

    Time = Range("A1")

    If Time > 26 Then
        E = Chr(Int((Time - 1) / 26) + 64) & Chr(((Time - 1) Mod 26) + 65)
    Else
        E = Chr(Time + 64)
    End If

End Sub

备注

Chr returns 基于 ASCII value

的字符

更简单更可靠的方法是使用 Excel 已经提供的,这意味着 "every letter is associated to a number in the ranges":

Public Function numberToLetter(ByVal myNumber As Integer) As String
    numberToLetter = Split(Cells(1, myNumber).Address, "$")(1)
End Function