有人有一段Excel VBA函数可以根据给定的数字返回相应的列字母吗?
例如输入100,应该返回CV
。
有人有一段Excel VBA函数可以根据给定的数字返回相应的列字母吗?
例如输入100,应该返回CV
。
这是基于@DamienFennelly的答案的一个函数。如果您给我点赞,请也给他点赞!:P
Function outColLetterFromNumber(iCol as Integer) as String
sAddr = Cells(1, iCol).Address
aSplit = Split(sAddr, "$")
outColLetterFromNumber = aSplit(1)
End Function
使用Excel功能非常简单:使用Range.Cells.Address
属性,方法如下:
strCol = Cells(1, lngRow).Address(xlRowRelative, xlColRelative)
这将返回第一行所需列的地址。从1
中取出它:
strCol = Left(strCol, len(strCol) - 1)
Mid(Cells(X,Y).Address, 2, instr(2,Cells(X,Y).Address,"$")-2)
Mid(Cells(1,val(range("Cellname").Column)).Address, 2, instr(2,Cells(1,val(range("Cellname").Column)).Address,"$")-2)
我来晚了,但我想提供另一个答案,没有其他人提到涉及数组。你可以使用简单的字符串操作完成此操作。
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
当你有以$A$1
格式的输入时,使用Mid
函数,从第二个字符开始计算,以便将第一个$
排除在外。接下来,使用InStr
函数查找字符串中第二个$
出现的位置,并从起始位置减去2。
这样做的好处是能够适应所有可能的列范围。因此,ColLetter(1)
返回"A",ColLetter(16384)
返回"XFD",这是我Excel版本中最后一个可能的列。
这里有一条简单的命令可以使用。
ColumnLetter = Mid(Cells(Row, LastColA).Address, 2, 1)
这种方法只适用于单个字母的列标识,但对于简单的情况非常有用。如果您需要它仅适用于两个字母的标识,则可以使用以下方法:
ColumnLetter = Mid(Cells(Row, LastColA).Address, 2, 2)
function GetColLetterFromNum(Sheet : Variant; Col : Integer) : String;
begin
Result := Sheet.Columns[Col].Address; // from Col=100 --> '$CV:$CV'
Result := Copy(Result, 2, Pos(':', Result) - 2);
end;
获取列名的简单方法
Sub column()
cell=cells(1,1)
column = Replace(cell.Address(False, False), cell.Row, "")
msgbox column
End Sub
我希望它能帮到你 =)
ColumnLetter(COLUMN())
实现,但我认为如果它能聪明地理解就更好了。Public Function ColumnLetter(Optional ColumnNumber As Long = 0) As String
If ColumnNumber = 0 Then
ColumnLetter = Split(Application.Caller.Address(True, False, xlA1), "$")(0)
Else
ColumnLetter = Split(Cells(1, ColumnNumber).Address(True, False, xlA1), "$")(0)
End If
End Function
IF
测试的存在,它会比 brettdj 的答案稍微慢一点。但如果该函数被重复使用多次且次数非常大,可能会感受到这种差别。Function fColLetter(iCol As Integer) As String
On Error GoTo errLabel
fColLetter = Split(Columns(lngCol).Address(, False), ":")(1)
Exit Function
errLabel:
fColLetter = "%ERR%"
End Function
brettdj的解决方案非常好,但如果您像我一样因同样的原因寻找潜在解决方案,我想提供我的另一种解决方案。
我遇到的问题是根据MATCH()函数的输出滚动到特定列。我选择临时切换引用样式从A1到R1C1,而不是将列号转换为其对应的列字母。这样,我就可以直接滚动到列号,而不必使用VBA函数。要轻松切换两种引用样式,您可以使用此VBA代码:
Sub toggle_reference_style()
If Application.ReferenceStyle = xlR1C1 Then
Application.ReferenceStyle = xlA1
Else
Application.ReferenceStyle = xlR1C1
End If
End Sub