【问题标题】:Get column name from column number?从列号获取列名?
【发布时间】:2016-05-22 21:49:44
【问题描述】:

我在一张纸上有几个命名的列。我想将列号发送到将返回列名的函数。

例如,如果第 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

我怎样才能让这段代码工作?

【问题讨论】:

  • 试试getColName = Cells(1, colNumber).Value
  • excel 中的列没有名称。您可以命名一个范围,或者正如@Fadi 所说,找到第一个单元格的值,其中通常是描述列中值的标签。
  • @Scott Craner,你误解了我的意思。我已将整个第 1 列(或 A 列,如果您愿意)命名为“apple”(或 [apple],如果您愿意)。我想将列号(在本例中为 1)发送到返回列名的函数。
  • Here 是我问题的答案。抱歉重复上一个问题
  • getColName = Cells(1, colNumber).EntireColumn.Name.Name

标签: excel vba


【解决方案1】:

试试这个:

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

【讨论】:

  • 这不能回答问题。您的答案对应于question。当前问题已回答并解决there
【解决方案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 的值还没有错误处理。在这种情况下,函数只会返回任何废话。自己动手做...

【讨论】:

  • 不是问题的答案
【解决方案3】:
Sub GetColumnNameFromRange()
    Dim Colname As String
    For Each cell In Selection.Cells
        If cell.EntireColumn.Hidden = False Then
            Colname = Mid(cell.Address, 2, Len(cell.Address) - (Len(cell.Row) + 2))
            MsgBox Colname
        End If
    Next cell
End Sub

【讨论】:

【解决方案4】:
Dim ColAdr as String, ColNo as Long, ColName as String
Function ColName (ColNo as Long)
ColAdr = ThisWorkbook.Sheets("Sheet1").Cells(1, ColNo).Address(RowAbsolute:=True, ColumnAbsolute:=False)
ColName = Left(ColAdr, InStr(1, ColAdr, "$") - 1)
End function

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以在help center找到更多关于如何写好答案的信息。
【解决方案5】:
ColumnNumber = i 'where i need to be a integer number > 0 and <= 16,384
ColumnName = cells(1,i).Address(False, False)

如果行和列引用是绝对的还是相对的,Adress() 中的参数是相关的。在上面的这种情况下,他们将是亲戚。

一切都结束了。就这么简单。

【讨论】:

    猜你喜欢
    • 2013-07-16
    • 2013-10-09
    • 2019-11-01
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多