从列号中获取列名?

时间:2016-02-11 21:56:47

标签: excel-vba vba excel

我在工作表上有几个命名列。我想将列号发送到将返回列名的函数。

例如,如果第1列被命名为" apple",我想将列号1传递给返回列名" apple"的函数。我的尝试:

Function getColName(colNumber As Integer) As String
'return column name when passed column number

    getColName = Cells(1, colNumber).Column.Name

End Function

如何让这段代码生效?

2 个答案:

答案 0 :(得分:2)

试试这个:

set cell_address = Worksheet("Sheet1").Cells(1,1)
MsgBox cell_address.address(RowAbsolute:=False, ColumnAbsolute=False) 

'返回A1 您也可以在Range("A1")中使用它并获得更多功能。

**Note**: RowAbsolute:=False, ColumnAbsolute=False are optional 

了解更多信息:

<强> https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-address-property-excel

表示非vba: https://exceljet.net/formula/convert-column-number-to-letter

答案 1 :(得分:-2)

如果您需要索引中的列字母, 这是我为此编写的函数:

Function colNameOf(ByVal colindex As Long) As String
    
    Dim overAlphabetic, charId As Long
    charId = colindex Mod 26
    colindex = colindex - charId
    overAlphabetic = colindex / 26
    
    If charId = 0 Then
        charId = 26
        overAlphabetic = overAlphabetic - 1
    End If
    
    Dim overAlphStr As String
    overAlphStr = ""
    
    If overAlphabetic > 0 Then
        overAlphStr = colNameOf(overAlphabetic)
    End If
    
    Dim lastChar
    lastChar = ChrW(charId + 64)
    
    colNameOf = overAlphStr & lastChar
    
End Function

注意,对于小于1的值,尚无错误处理。在这种情况下,该函数只会返回任何废话。 DIY ...