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

时间:2015-01-18 22:55:13

标签: 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

2 个答案:

答案 0 :(得分:2)

更简单,更可靠的方法是使用Excel已经提供的内容,这意味着"每个字母都与范围内的数字相关联":

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

答案 1 :(得分:1)

这是一种方式。

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会根据ASCII value

返回一个字符