My Comments
ARich gives a good solution and shows the method I used for a while but Sancarn is right, its not optimal. It's a little slower, will cause errors if the wrong input is given, and is not very robust. Sancarn is on the right track, but lacks a little error checking: for example, getColIndex("_") and getColIndex("AE"), will both return 31. Other non-letter characters (ex: "*") sometimes return various negative values.
Working Function
Here is a function I wrote that will convert a column letter into a number. If the input is not a column on the worksheet, it will return -1 (unless AllowOverflow is set to TRUE).
Function ColLetter2Num(ColumnLetter As String, Optional AllowOverflow As Boolean) As Double
'Converts a column letter to a number (ex: C to 3, A to 1, etc). Returns -1 if its invalid.
' @ColumnLetter - the letter(s) to convert to a number.
' @AllowOverflow - if TRUE, can return a number greater than the max columns.
On Error GoTo invalidCol
If Len(ColumnLetter) = 0 Then GoTo invalidCol
Dim thisChar As String
For i = 1 To Len(ColumnLetter) 'for each character in input
thisChar = Mid(ColumnLetter, i, 1) 'get next character
If Asc(UCase(thisChar)) >= 65 And Asc(UCase(thisChar)) <= 90 Then 'if the character is a letter
ColLetter2Num = ColLetter2Num + (26 ^ (Len(ColumnLetter) - i)) * (Asc(UCase(thisChar)) - 64) 'add its value to the return
Else
GoTo invalidCol 'if the character is not a letter, return an error
End If
If AllowOverflow = False And (ColLetter2Num = 0 Or ColLetter2Num > Columns.Count) Then
'if the value is not inside the bounds of the sheet, return an error and stop
invalidCol:
ColLetter2Num = -1 'error
Exit Function 'stop checking
End If
Next i
End Function
Examples
Sub test()
Debug.Print ColLetter2Num("A") 'returns 1
Debug.Print ColLetter2Num("IV") 'returns 256 (max columns for excel 2003 and prior))
Debug.Print ColLetter2Num("XFD") 'returns -1 (invalid because IV is the last column for .xls workbooks)
Debug.Print ColLetter2Num("XFD", True) 'returns 16384 (does not return -1 because AllowOverflow = TRUE)
Debug.Print ColLetter2Num("A_", True) 'returns -1 (invalid because "_" is not a column)
Debug.Print ColLetter2Num("132", True) 'returns -1 (invalid because "1" is not a column)
If ColLetter2Num("A") <> -1 Then
Debug.Print "The input is a valid column on the sheet."
Else
Debug.Print "The input is NOT a valid column on the sheet."
End If
End Sub