Sunday 24 March 2019

How to get the current column name in Excel?


What is the function to get the current line number and the current column name for a cell in Excel?



Answer



You can use the ROW and COLUMN functions to do this. If you omit the argument for those formulas, the current cell is used. These can be directly used with the OFFSET function, or any other function where you can specify both the row and column as numerical values.


For example, if you enter =ROW() in cell D8, the value returned is 8. If you enter =COLUMN() in the same cell, the value returned is 4.


If you want the column letter, you can use the CHAR function. I do not recommend the use of letters to represent the column, as things get tricky when passing into double-letter column names (where just using numbers is more logical anyways).


Regardless, if you should still want to get the column letter, you can simply add 64 to the column number (64 being one character less then A), so in the previous example, if you set the cell's value to =CHAR(COLUMN()+64), the value returned would be D. If you wanted a cell's value to be the cell location itself, the complete formula would be =CHAR(COLUMN()+64) & ROW().




Just an FYI, I got 64 from an ASCII table. You could also use the CODE formula, so the updated formula using this would be =CHAR(COLUMN() + CODE("A") - 1). You have to subtract 1 since the minimum value of COLUMN is always 1, and then the minimum return value of the entire formula would be B.


However, this will not work with two-letter columns. In that case, you need the following formula to properly parse two-letter columns:


=IF(COLUMN()>26,IF(RIGHT(CHAR(IF(MOD(COLUMN()-1,26)=0,1,MOD(COLUMN()-1,26))+64),1)="Y",CHAR(INT((COLUMN()-1)/26)+64) & "Z",CHAR(INT((COLUMN()-1)/26)+64) & CHAR(IF(MOD(COLUMN(),26)=0,1,MOD(COLUMN(),26))+64)),CHAR(COLUMN()+64))&ROW()

I'm not sure if there is an easier way to do it or not, but I know that works from cell A1 to ZZ99 with no problems. However, this illustrates why it's best to avoid the use of letter-based column identifiers, and stick with pure number-based formulas (e.g. using the column number instead of letter with OFFSET).


No comments:

Post a Comment

How can I VLOOKUP in multiple Excel documents?

I am trying to VLOOKUP reference data with around 400 seperate Excel files. Is it possible to do this in a quick way rather than doing it m...