Excel column number from column name
Solution 1:
I think you want this?
Column Name to Column Number
Sub Sample()
ColName = "C"
Debug.Print Range(ColName & 1).Column
End Sub
Edit: Also including the reverse of what you want
Column Number to Column Name
Sub Sample()
ColNo = 3
Debug.Print Split(Cells(, ColNo).Address, "$")(1)
End Sub
FOLLOW UP
Like if i have salary field at the very top lets say at cell C(1,1) now if i alter the file and shift salary column to some other place say F(1,1) then i will have to modify the code so i want the code to check for Salary and find the column number and then do rest of the operations according to that column number.
In such a case I would recommend using .FIND
See this example below
Option Explicit
Sub Sample()
Dim strSearch As String
Dim aCell As Range
strSearch = "Salary"
Set aCell = Sheet1.Rows(1).Find(What:=strSearch, LookIn:=xlValues, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
If Not aCell Is Nothing Then
MsgBox "Value Found in Cell " & aCell.Address & _
" and the Cell Column Number is " & aCell.Column
End If
End Sub
SNAPSHOT
Solution 2:
While you were looking for a VBA solution, this was my top result on google when looking for a formula solution, so I'll add this for anyone who came here for that like I did:
Excel formula to return the number from a column letter (From @A. Klomp's comment above), where cell A1 holds your column letter(s):
=column(indirect(A1&"1"))
As the indirect function is volatile, it recalculates whenever any cell is changed, so if you have a lot of these it could slow down your workbook. Consider another solution, such as the 'code' function, which gives you the number for an ASCII character, starting with 'A' at 65. Note that to do this you would need to check how many digits are in the column name, and alter the result depending on 'A', 'BB', or 'CCC'.
Excel formula to return the column letter from a number (From this previous question How to convert a column number (eg. 127) into an excel column (eg. AA), answered by @Ian), where A1 holds your column number:
=substitute(address(1,A1,4),"1","")
Note that both of these methods work regardless of how many letters are in the column name.
Hope this helps someone else.