Column Numbers To Letters
Chip Pearson posted this solution to the newsgroups for finding the column letters when you know the column numbers:
Function ColLetter(ColNumber As Integer) As String
ColLetter = Left(Cells(1, ColNumber).Address(False, False), _
1 - (ColNumber > 26))
End Function
Very smart function, in my opinion. Sometime before the year 3,000, Microsoft will hopefully increase the number of columns in Excel (Hey, I can dream can’t I). The challenge before you is to write a function that converts a column number to its letter equivalent assuming columns go to ZZZZ. That’s about 450,000 columns - maybe more than I need.
I was just going to whip up a short function to do this and post it, but after 10 minutes I still couldn’t do it. Rather than admit defeat, I turned this post into a challenge for you. It’s Friday, you weren’t going to work anyway, were you?
Juan Pablo:
Am I getting annoying ?
21 May 2004, 12:26 pmFunction ColLetter(ColNumber As Long) As String
ColLetter = Application.Substitute(Cells(1, ColNumber).Address(False, False), “1″, “”)
End Function
Dick:
Very nice! Needs some error checking if the number passed is too big, easy enough. Also, what if the activesheet is a chart sheet? What if all the sheets in the activeworkbook are chart sheets?
This is exactly the easy solution that I couldn’t find. Now if we can avoid the non-worksheet situation, it will be perfect.
21 May 2004, 2:01 pmBrian:
Howsabout a kludgey untested formula for letter to column? (Yes, I did misread the original challenge. Ho hum.)
21 May 2004, 2:32 pm=IF(LEN(A1)<4,0,26^3*(1+CODE(MID(UPPER(A1),LEN(A1)-3,1))-CODE(”A”)))+IF(LEN(A1)<3,0,26^2*(1+CODE(MID(UPPER(A1),LEN(A1)-2,1))-CODE(”A”)))+IF(LEN(A1)<2,0,26*(1+CODE(MID(UPPER(A1),LEN(A1)-1,1))-CODE(”A”)))+IF(LEN(A1)
JWalk:
This seems to work for column letters up to ZZ (702 columns).
Function ColLetter(ColNumber As Long) As String
Dim x2 As Double, x3 As Integer
Dim x4 As String, x5 As Integer
Dim x6 As String, x7 As String
If ColNumber > 702 Or ColNumber < 1 Then Exit Function
x2 = (ColNumber - 1) / 26
x3 = Int(x2)
x4 = Chr(x3 + 64)
x5 = ColNumber Mod 26
If x4 = “@” Then x6 = “” Else x6 = x4
If x5 = 0 Then x7 = “Z” Else x7 = Chr(x5 + 64)
ColLetter = x6 & x7
End Function
I figured this out using worksheet formulas, and then converted the formulas to VBA.
In Row 1, put the numbers 1-256
A2: =(A1-1)/26
A3: =TRUNC(A2)
A4: =CHAR(A3+64)
A5: =MOD(A1,26)
A6: =IF(A4=”@”,”",A4)
A7: =IF(A5=0,”Z”,CHAR(A5+64))
A8: =A6&A7
Then copy A2:A8 across.
It doesn’t solve the problem, but at least it gave me something to do for the past 15 minutes.
21 May 2004, 2:53 pmJuan Pablo:
This works if the activesheet is a chart sheet or even if no workbook are visible:
Function ColLetter(ColNumber As Long) As String
21 May 2004, 3:11 pmOn Error Resume Next
ColLetter = Application.Substitute(Application.ConvertFormula(”R1C” & ColNumber, _
xlR1C1, xlA1, 4), “1″, “”)
End Function
Tommy Bak:
This is only testet to 702 columns
Columnnumber is written in A1
=LEFT(ADRESS(1;A1;4);FIND(1;ADDRESS(1;A1;4))-1)
23 May 2004, 5:23 amGary Waters:
Sorry Gary, I’m changing your comment. I can’t post comments to this post anymore because the submit button is off the screen. To read Gary’s comment, go here
http://www.dicks-blog.com/excel/garycolletter.htm
24 May 2004, 10:06 pmHarald Staff:
I believe this will work:
Function Num2Let(L As Long) As String
25 May 2004, 6:22 amDim s0 As String, s1 As String, S2 As String, s3 As String
If L > 18278 Then s0 = Chr((Int((L - 18279) / 17576) Mod 26) + 65)
If L > 702 Then s1 = Chr((Int((L - 703) / 676) Mod 26) + 65)
If L > 26 Then S2 = Chr(Num2Let & (Int((L - 27) / 26)) Mod 26 + 65)
s3 = Chr(((L - 1) Mod 26) + 65)
Num2Let = s0 & s1 & S2 & s3
End Function
J-Walk:
Wow, I think Harald wins.
2 June 2004, 1:38 pmHarald Staff:
Thanks John. I always wanted a Corvette
I have no idea how the
2 June 2004, 5:16 pm“Num2Let & ”
in line 5 survived the final tests. Please pretend it’s not there.
kevboy:
I have a secret message for Harald, Dick, and anyone else who might be bored right now:
1000, 9, 217287, 535, 119, 253, 319778, 357181, 43661.
2 June 2004, 5:45 pmDick:
247, 131174, 17311, 217287, 254
2 June 2004, 10:22 pmGary Waters:
Very Good Harald. Here is my new improved formula that covers all positive long integers, based on Harald’s insightful fuction:
Function ConvertNumberToColumnLetter2(ByVal colNum As Long) As String
5 June 2004, 2:47 pmDim i As Long, x As Long
For i = 6 To 0 Step -1
x = (1 - 26 ^ (i + 1)) / (-25) - 1 ‘ Geometric Series formula
If colNum > x Then
ConvertNumberToColumnLetter2 = ConvertNumberToColumnLetter2 & Chr(((colNum - x - 1)\ 26 ^ i) Mod 26 + 65)
End If
Next i
End Function
Gary Waters:
Sorry Dick, I promise this will be my last say on this subject. I slightly improved on my last posting, using the Geometric Series Sum Formula, to limit the number of iterations:
Function ColumnLetter(ByVal colNum As Long) As String
6 June 2004, 5:08 amDim i As Long, x As Long
For i = Int(Log(CDbl(25 * (CDbl(colNum) + 1))) / Log(26)) - 1 To 0 Step -1
x = (26 ^ (i + 1) - 1) / 25 - 1
If colNum > x Then
ColumnLetter = ColumnLetter & Chr(((colNum - x - 1) \ 26 ^ i) Mod 26 + 65)
End If
Next i
End Function
Dick:
Gary: Keep them coming, this is good stuff.
6 June 2004, 9:19 amHarald Staf:
Very nice, Gary. That’s a piece of art.
What we’d need now is the reverse function. All work and no play this week…
Function ColNum(Byval ColumnLetter as string) as Long
7 June 2004, 8:06 am‘anyone ?
Harald Staff:
Very nice, Gary. That’s a piece of art.
What we’d need now is the reverse function. All work and no play this week…
Function ColNum(Byval ColumnLetter as string) as Long
7 June 2004, 8:07 am‘anyone ?
Roger Crawley:
I used Harald’s Function to devise a function that could handle more columns. It is a more simplistic function than Gary’s and will go no further than column ZZZZZZ:
Function ColNum2Let(ColumnNumber As Long) As String
Dim CL As String, CN As Long, S As Long, N As Integer, Ns As Long, c As Integer, e As Integer
Let CN = ColumnNumber
Let N = 0
Let Ns = 0
Do
Let N = N + 1
Let Ns = Ns + 26 ^ N
Loop Until CN < = Ns
Let CL = ""
For c = 1 To N
Let S = 0
For e = 0 To c - 1
Let S = S + 26 ^ e
Next e
Let CL = Chr((Int((CN - S) / (26 ^ (c - 1))) Mod 26) + 65) & CL
Next c
ColNum2Let = CL
End Function
Then using this as a base I have written a reverse function (which can handle all positive long integers, i.e. up to column FXSHRXW):
Function ColLet2Num(ColumnLetter As String) As Long
16 June 2004, 11:38 amDim CL As String, CN As Long, N As Integer, S As Long, Se As Integer, c As Integer, t As String, ti As Integer, A As Long
Let CL = ColumnLetter
Let N = Len(CL)
Let S = 0
For Se = 0 To N - 1
Let S = S + 26 ^ Se
Next Se
Let t = ""
Let A = 0
For c = 1 To N
t = UCase(Mid(CL, c, 1))
Let ti = 65
Do Until Chr(ti) = t
Let ti = ti + 1
If ti > 90 Then
Let CN = “Error”
GoTo 1
End If
Loop
Let A = A + ((ti - 65) * (26 ^ (N - c)))
Next
Let CN = S + A
1 ColLet2Num = CN
End Function
Tushar Mehta:
I am curious as to why people prefer Harald’s solution to Juan Pablo’s Substitute(ConvertFormula()) one-liner. It would appear the latter would cover *any* number of columns not just restrict itself to those with four letter designations.
23 January 2005, 7:44 amThe Contrarian:
To really use a large number of columns — more than 10?
— one really needs to change the addressing paradigm. I find that I often switch to R1C1 mode when I have to scroll horizontally to see the entire worksheet. Where the f*** is AM? Or GD?
And, that would take care of the need for functions that provide column letters. Wouldn’t it?
In fact, the A1 and R1C1 conventions are like the QWERTY and Dvorak keyboard layouts or VHS and Betamax. In each case, the latter is/was far superior but the former dominates/won the marketplace.
23 January 2005, 7:54 amanonymous:
Why don’t you just use the built-in address function to generate column names from row/column numbers?
24 January 2005, 4:27 pmEdd:
Col_Letter = Left(Cells(1, Col_Num).Address(False, False), 1 + Fix(Col_Num ^ (1 / 26)))
I think that this works however many columns there are
3 November 2005, 11:04 amEdd:
ignore that its wrong!
4 November 2005, 5:11 amThe Social Programmer » Blog Archive » Excel: Column Number to Letter(s):
[…] So I’m grateful for the existence of Dick’s Blog and in particular this post. […]
22 November 2005, 12:20 pmDie_Another_Day:
Function getColLet(ColumnNumber As Integer) As String
Dim colLet() As String
On Error Resume Next
colLet = Split(Cells(1, ColumnNumber).Address, “$”)
If colLet(1) = “” Then
getColLet = “error”
MsgBox “This version of Excel does not support ” & ColumnNumber & ” Columns”
Else
getColLet = colLet(1)
End If
On Error GoTo 0
End Function
…except for the non-worksheet problem. Hmmm.
Die_Another_Day
30 January 2006, 10:02 amDie_Another_Day:
And now for people who want to do this when the Active Sheet is a chart…
Function getColLet(ColumnNumber As Integer) As String
Dim colLet() As String
Dim aWorkbook As Workbook ‘Active Workbook
Dim nWorkbook As Workbook ‘New Workbook
Application.ScreenUpdating = False ‘Hide screen updates while program is running
Set aWorkbook = ActiveWorkbook ‘Get the active workbook so it can be restored before exiting function
‘Create new workbook so we can be sure we’re looking at a worksheet
Set nWorkbook = Application.Workbooks.Add
nWorkbook.Sheets(1).Activate ‘Activate Sheet1 on the new workbook
‘Don’t pause on error in event that we passed a column that isn’t supported in Excel
On Error Resume Next
colLet = Split(Cells(1, ColumnNumber).Address, “$”) ‘Split Address into array using the “$” as a delimiter
If colLet(1) = “” Then ‘error handler
getColLet = “error”
MsgBox “This version of Excel does not support ” & ColumnNumber & ” Columns”
Else
getColLet = colLet(1)
End If
On Error GoTo 0 ‘Reset error handling to default
nWorkbook.Close (False) ‘Close new workbook without saving
aWorkbook.Activate ‘Activate the previously active workbook
Application.ScreenUpdating = True ‘Turn Screen updating back on
End Function
30 January 2006, 2:04 pmJon Peltier:
How does the overhead of opening and closing a workbook improve on the earlier proposed solutions? It also limits one to 256 columns, or letters only up to IV.
31 January 2006, 6:39 amDie_Another_Day:
Actually John, this is not specifically limited to 256 columns. Technically it is limited to the max number of columns for the current version of Excel. If a future version of Excel is capable of > 256 columns it won’t return an error this way I can make sure the column really does exist. However I’m not sure if future versions of Excel will be backwards compatible with the code.
Die_Another_Day
P.S. Thanks for taking the time to look at my code
31 January 2006, 10:05 amJon Peltier:
Yeah, okay, it’s not limited to 256, it’s limited to the current column count, which is 256. Many of the other approaches don’t have this limit.
I was really more concerned with opening and closing a workbook just to generate a text string. Worksheets.Add would be less of a performance hit, I’m sure. But I’d investigate one of the other approaches. I might even convert to R1C1 notation.
31 January 2006, 4:09 pmDie_Another_Day:
Jon, here’s a more “unique” way of doing this… I view it as a number base problem and found it to be quite simple to go both ways.
Function ColNumToLet(ByVal ColumnNumber As Integer) As String
Dim Remain As Double
Dim Quot As Integer
If ColumnNumber 26
ColNumToLet = Chr(Quot Mod 26 + 64) & ColNumToLet
Quot = WorksheetFunction.RoundDown(Quot / 26, 0)
Loop
ColNumToLet = Chr(Quot + 64) & ColNumToLet
End Function
Function ColLetToNum(ByVal otherBaseNumber As String) As Double
Dim index As Double
Dim digits As String
Dim digitValue As Double
digits = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
For index = 1 To Len(otherBaseNumber)
digitValue = InStr(1, digits, Mid$(otherBaseNumber, index, 1), vbTextCompare)
ColLetToNum = ColLetToNum * 26 + digitValue
Next
End Function
this has no limits on number of columns which could be a problem…
Let me know what you think. feel free to email me if you wish. chick65stang@yahoo.com
1 February 2006, 5:08 pmDie_Another_Day:
Crap forgot to update the Argument names for the ColLetToNum Function…
Function ColLetToNum(ByVal ColumnLetter As String) As Double
Dim index As Double
Dim digits As String
Dim digitValue As Double
digits = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”
For index = 1 To Len(ColumnLetter)
digitValue = InStr(1, digits, Mid$(ColumnLetter, index, 1), vbTextCompare)
ColLetToNum = ColLetToNum * 26 + digitValue
Next
End Function
1 February 2006, 5:12 pmJon Peltier:
Yeah, number base is the way to go.
1 February 2006, 6:42 pmRob van Gelder:
I’ve sort of been following this thread and remembered I had something on my website.
Number to Column Letter:
strColumn = Split(Columns(lngColumn).Address(, False), “:”)(1)
1 February 2006, 11:07 pmchandu:
how can I cahnge the column numbers back to letters?
6 February 2006, 1:58 pmDie_Another_Day:
Jon, my previous code had some flaws in it. I believe this code should work, that is unless you have columns in excess of 3.267 Quadrillion
I think it must be the limit of the double precision number. Note that I had to make my own “mod” function, this is due to the fact that the built in VBA mod function is a long data type and would only support columns up to 32,767.
Charles
Function ColNumToLet(ByVal ColumnNumber As Double) As String
If ColumnNumber 3.267215265265262E+15 Then
ColNumToLet = “Error”
Else
ColNumToLet = “”
If ColumnNumber 26
If myMod(ColumnNumber, 26) = 0 Then
ColNumToLet = “Z” & ColNumToLet
ColumnNumber = ColumnNumber - 1
Else
ColNumToLet = Chr(myMod(ColumnNumber, 26) + 64) & ColNumToLet
End If
ColumnNumber = WorksheetFunction.RoundDown(ColumnNumber / 26, 0)
Loop
If Not ColumnNumber = 0 Then ColNumToLet = Chr(ColumnNumber + 64) & ColNumToLet
End If
End If
End Function
Function myMod(Numerator As Double, Denominator As Double) As Double
10 February 2006, 9:39 ammyMod = Numerator - (WorksheetFunction.RoundDown(Numerator / Denominator, 0) * Denominator)
End Function
Die_Another_Day:
Sorry, something got messed up when I posted previously.
Function ColNumToLet(ByVal ColumnNumber As Double) As String
10 February 2006, 9:45 amIf ColumnNumber 3.26721526526526E+15 Then
ColNumToLet = “Error”
Else
ColNumToLet = “”
If ColumnNumber 26
If myMod(ColumnNumber, 26) = 0 Then
ColNumToLet = “Z” & ColNumToLet
ColumnNumber = ColumnNumber - 1
Else
ColNumToLet = Chr(myMod(ColumnNumber, 26) + 64) & ColNumToLet
End If
ColumnNumber = WorksheetFunction.RoundDown(ColumnNumber / 26, 0)
Loop
If Not ColumnNumber = 0 Then ColNumToLet = Chr(ColumnNumber + 64) & ColNumToLet
End If
End If
End Function
Die_Another_Day:
Ok, I think some weird HTML thing is killing my greater than less than stuff.
line 2 should read:
If ColumnNumber “Less Than” 1 or ColumnNumber “Greater Than” 3.26721526526526E+15 Then
10 February 2006, 9:50 amEric:
Based on Rob van Gelder’s above, the following function gets the column letter of any type of range (including cells):
‘ Description: Returns the column letter for a cell or column input Range; returns empty string (”") for a row input Range
Private Function rangeLet(ByVal inputRange As Range) As String
‘to understand how this works, here are examples of the inputRange.Address(RowAbsolute:=True, ColumnAbsolute:=False) for:
‘ - a cell (C1) “C$1″
‘ - a column (C) “C:C”
‘ - a row (1) “$1:$1″
‘it gets all characters in the string before the first “$” from everything before the (first) “:”
rangeLet = Split(Split(inputRange.Address(RowAbsolute:=True, ColumnAbsolute:=False), “:”)(0), “$”)(0)
End Function
30 November 2007, 12:58 pmZach:
I’m glad this got resurrected. I just wrote the same function today for probably the 4th time. I thought my latest implementation was slick, but I don’t compare to the one liners. I think Juan Pablo is the winner here. So I feel a little bit better that I can correct even his sweet one line by changing the application.subsitute to a simple replace.
It’s funny how there are so many ways to tackle the same issue. I’ll bet every single one of these approaches differs from the other in execution time by no more than .001 seconds.
30 November 2007, 8:04 pmkeepITcool:
Dim p As Long
While c
p = 1 + (c - 1) Mod 26
c = (c - p) \ 26
ColumnLetter = Chr$(64 + p) & ColumnLetter
Wend
End Function
Elegantly pure math. None faster.
3 December 2007, 3:56 amphil:
need help to figure out formula to make 2 letters equal quantities and then take that value of which ever letter you put in that cell and use it in another formula. (i.e. column A reads 2000 and column B could read "S" which should equal "1" or "P" which should equal "0" then column C takes 2000 times "s"(which equals 1) and calculates 2000 in column C or 2000 times "p" (which equals 0) then it would calculate 0 in column C
20 July 2008, 5:01 pmElias:
Try this,
C1 =A1*(B1="S")
Regards
21 July 2008, 11:02 am