我需要显示一个msgbox,显示上次使用的列。
现在显示列数值,但是可以将其转换为等效的字母字符吗?
实施例。第5栏= E栏。
由于
答案 0 :(得分:2)
我设法获得了2种方法。一个依赖于excel Cells
,因此如果您使用无效列,则会失败:
Function NumToLetter(q As Long) As String
Dim Add As String
'Ignore error so it fails on an invalid cell
On Error Resume Next
Add = Cells(1, q).Address
If Len(Add) Then
NumToLetter = Mid(Add, 2, InStr(2, Add, "$") - 2)
Else
NumToLetter = "Invalid Cell"
End If
End Function
另一个使用base 26,并且仅限于long
的最大值:
Function Num2Letter(q As Long) As String
Dim r As Long
While q > 0
r = q Mod 26
If r = 0 Then r = 26 ' needed for column Z
Num2Letter = Chr(64 + r) & Num2Letter
q = Int(q / 26) + (r = 26) ' fix for column Z
Wend
End Function
使用消息框测试这些值:
msgbox "Column 2445 is " & NumToLetter(2445) & " or " Num2Letter(2445)
第2445栏是CPA或CPA
msgbox "Column 42445 is " & NumToLetter(42445) & " or " Num2Letter(42445)
列42445是无效单元格或BJTM
msgbox "Column -1 is " & NumToLetter(-1) & " or " Num2Letter(-1)
列-1是无效单元格或
答案 1 :(得分:0)
这适用于A到ZZ栏(正如Sean Cheshire的评论中所指出的那样):
Function ColLetter(ColNumber As Integer) As String
ColLetter = Left(Cells(1, ColNumber).Address(False, False), 1 - (ColNumber > 26))
End Function
使用:MsgBox ColLetter(oRangeObject.Column)