I’m writing a vbs script to extract some data from an excel spreadsheet. Currently using the function:
To get cell values, this allows me to do maths on the column number, e.g. add three to move across three columns. But in some instances I want to specify which Columns to get by letter:
I therefore need to write a vbs function to convert column letter to numbers E => 5. Needs to be able to handle a spreadsheet more than 26 cols wide.
I’ve seen lots of functions on the internet and SO for doing the opposite but not found much for doing the conversion this way.
This code will run without Excel:
Function ColNum(strCol As String) As Integer Dim i As Integer, col As Integer For i = Len(strCol) To 1 Step -1 col = col + (Asc(Mid(strCol, i, 1)) - 64) * (26 ^ (i - 1)) Next ColNum = col End Function
Alternatively, in Excel, you can simply use this:
Function ColNum(strCol As String) As Integer ColNum = Range(strCol & "1").Column End Function
To convert a column number to a letter you enter this formula:
=LEFT(ADDRESS(1,3,4)) (returns the column letter for the cell C1=C)
But this is still not satisfactory because if you insert a column before the column C the number 3 won’t change to 4, so here is a fix:
Hope this helps.
This is especially helpful when you need to create strings that specify a cell range for example.