How to get the column number from column name in Excel using Excel macro?
相关问题
- Excel sunburst chart: Some labels missing
- Error handling only works once
- Error handling only works once
- Excel formula in VBA code
- Excel VBA run time error 450 from referencing a ra
相关文章
- Get column data by Column name and sheet name
- programmatically excel cells to be auto fit width
- Unregister a XLL in Excel (VBA)
- Unregister a XLL in Excel (VBA)
- How to prevent excel from truncating numbers in a
- numeric up down control in vba
- Declare a Range relative to the Active Cell with V
- What's the easiest way to create an Excel tabl
In my opinion the simpliest way to get column number is:
Sub Sample() ColName = ActiveCell.Column MsgBox ColName End Sub
Write and run the following code in the Immediate Window
For example
?cells(,"BYL").column
will return 2014. The code is case-insensitive, hence you may write?cells(,"byl").column
and the output will still be the same.You could skip all this and just put your data in a table. Then refer to the table and header and it will be completely dynamic. I know this is from 3 years ago but someone may still find this useful.
Example code:
You can also use :
You can even use this reference system in worksheet formulas as well. Its very dynamic.
Hope this helps!
I think you want this?
Column Name to Column Number
Edit: Also including the reverse of what you want
Column Number to Column Name
FOLLOW UP
In such a case I would recommend using
.FIND
See this example belowSNAPSHOT
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):
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:
Note that both of these methods work regardless of how many letters are in the column name.
Hope this helps someone else.