How would you determine the column name (e.g. "AQ" or "BH") of the nth column in Excel?
Edit: A language-agnostic algorithm to determine this is the main goal here.
In a row of Excel, e.g. cell A1, enter the column number =column() In the row below, enter =Address(1,A1) This will provide the result $A$1.
I once wrote this function to perform that exact task:
public static string Column(int column) { column--; if (column >= 0 && column < 26) return ((char)('A' + column)).ToString(); else if (column > 25) return Column(column / 26) + Column(column % 26 + 1); else throw new Exception("Invalid Column #" + (column + 1).ToString()); }
Here is the cleanest correct solution I could come up with (in Java, but feel free to use your favorite language):
String getNthColumnName(int n) { String name = ""; while (n > 0) { n--; name = (char)('A' + n%26) + name; n /= 26; } return name; }
But please do let me know of if you find a mistake in this code, thank you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With