Function to convert column number to letter?

后端 未结 28 1540
灰色年华
灰色年华 2020-11-22 07:04

Does anyone have an Excel VBA function which can return the column letter(s) from a number?

For example, entering 100 should return CV.

28条回答
  •  情深已故
    2020-11-22 07:34

    So I'm late to the party here, but I want to contribute another answer that no one else has addressed yet that doesn't involve arrays. You can do it with simple string manipulation.

    Function ColLetter(Col_Index As Long) As String
    
        Dim ColumnLetter As String
    
        'Prevent errors; if you get back a number when expecting a letter, 
        '    you know you did something wrong.
        If Col_Index <= 0 Or Col_Index >= 16384 Then
            ColLetter = 0
            Exit Function
        End If
    
        ColumnLetter = ThisWorkbook.Sheets(1).Cells(1, Col_Index).Address     'Address in $A$1 format
        ColumnLetter = Mid(ColumnLetter, 2, InStr(2, ColumnLetter, "$") - 2)  'Extracts just the letter
    
        ColLetter = ColumnLetter
    End Sub
    

    After you have the input in the format $A$1, use the Mid function, start at position 2 to account for the first $, then you find where the second $ appears in the string using InStr, and then subtract 2 off to account for that starting position.

    This gives you the benefit of being adaptable for the whole range of possible columns. Therefore, ColLetter(1) gives back "A", and ColLetter(16384) gives back "XFD", which is the last possible column for my Excel version.

提交回复
热议问题