How can I compute any Excel column name from "A" to "ZZ" from an integer column number? This article will show you how.
I used to do a lot of VBA programming in Microsoft Word. I haven't done that in about four years, but occasionly still do VBA in Excel. In an application that I am working on, I save the contents of a spread sheet in XML in a database transaction table. In some cases, I am called upon to replicate the original spreadsheeet from the database and in addition add a variable number of columns to the output spreadsheet. The code that I wrote several years ago worked fine until the user added enough columns to exceed 26. Computing a column name from A to Z can be computed by the following line of code.
| Return Chr(Asc("A") + i) |
| ''' <summary> ''' Return string Excel column name for passed integer ''' column number. ''' ''' ''' <returns>string ''' <remarks> Private Function GetNextCol(ByVal i As Integer) As String Const A As String = "A" Dim firstInt As Integer = (i - 1) \ 26 Dim rounded As Integer = firstInt * 26 Dim secondAlpha As String = Chr((i - rounded - 1) + Asc(A)) Dim firstAlpha As String = String.Empty If firstInt > 0 Then firstAlpha = Chr(firstInt - 1 + Asc(A)) Else firstAlpha = secondAlpha secondAlpha = String.Empty End If Return (firstAlpha & secondAlpha).ToUpper End Function |
| Ask a Question, or give your feedback on my articles or products by going to the KnowDotNet Forum or by clicking on My Blog. | ![]() |