Convert an excel or spreadsheet column letter to its number in Pythonic fashion

前端 未结 17 1232
夕颜
夕颜 2020-12-09 04:18

Is there a more pythonic way of converting excel-style columns to numbers (starting with 1)?

Working code up to two letters:



        
17条回答
  •  一向
    一向 (楼主)
    2020-12-09 04:50

    This should do, in VBA, what you're looking for:

    Function columnNumber(colLetter As String) As Integer
    
        Dim colNumber As Integer
        Dim i As Integer
    
        colLetter = UCase(colLetter)
        colNumber = 0
        For i = 1 To Len(colLetter)
            colNumber = colNumber + (Asc(Mid(colLetter, Len(colLetter) - i + 1, 1)) - 64) * 26 ^ (i - 1)
        Next
    
        columnNumber = colNumber
    
    End Function
    

    You can use it as you would an Excel formula--enter column, in letters, as a string (eg, "AA") and should work regardless of column length.

    Your code breaks when dealing with three letters because of the way you're doing the counting--you need to use base 26.

提交回复
热议问题