Translate a column index into an Excel Column Name

前端 未结 15 2294
花落未央
花落未央 2020-11-27 20:41

Given a columns\' index, how can you get an Excel column name?

The problem is trickier than it sounds because it\'s not just base-26. The columns

15条回答
  •  温柔的废话
    2020-11-27 20:59

    I enjoy writing recursive functions, but I don't think it's necessary here. This is my solution in VB. It works up to column ZZ. If someone can tell me if it works for AAA to ZZZ that would be nice to know.

    Public Function TranslateColumnIndexToName(index As Integer) As String
    '
    Dim remainder As Integer
    Dim remainder2 As Integer
    Dim quotient As Integer
    Dim quotient2 As Integer
    '
    quotient2 = ((index) / (26 * 26)) - 2
    remainder2 = (index Mod (26 * 26)) - 1
    quotient = ((remainder2) / 26) - 2
    remainder = (index Mod 26) - 1
    '
    If quotient2 > 0 Then
        TranslateColumnIndexToName = ChrW(quotient2 + 65) & ChrW(quotient + 65) & ChrW(remainder + 65)
    ElseIf quotient > 0 Then
        TranslateColumnIndexToName = ChrW(quotient + 65) & ChrW(remainder + 65)
    Else
        TranslateColumnIndexToName = ChrW(remainder + 65)
    End If 
    

    End Function

提交回复
热议问题