Created
November 18, 2011 01:42
-
-
Save todd/1375284 to your computer and use it in GitHub Desktop.
Count Columns in a Spreadsheet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This is an overly complicated method I threw together to do something I could have easily done by | |
tallying on paper or something similar. That's not how I roll. | |
The method below will calculate the numerical position of a spreadsheet column based on its alphabetic | |
representation. I use a lot of VBA and Excel formulas at work that need this information to function | |
properly and I got tired to counting these columns manually - a real chore when you start getting into | |
columns represented by multiple characters. | |
NOTE: Excel is kind of inconsistent with its numbering format. Depending on what you're trying to | |
do with the output from this method, you may need to subtract 1 from the result if it relies on | |
zero-based numbering. | |
""" | |
# We need a string of characters in the alphabet | |
import string | |
alpha = string.lowercase | |
# The getPosition method | |
# @param: a string representation of a column in Excel (i.e., 'd', 'ba', etc.) | |
# We only need to account for params up to 'iv' (Excel's max number of allowed columns), | |
# but we're (theoretically) handling all possible combinations (i.e., 'bacd') | |
# @return: an integer representing the column number of the column string passed in | |
def getPosition(col): | |
# Return the position of the character in the alphabet if the parameter contains only one character | |
if col.__len__() == 1: | |
return alpha.index(col) + 1 | |
# Calculate the position of the column by combining the number of times the Excel columns | |
# have been through the alphabet with a recursive call to A) do more of the same or B) the | |
# position of the last character in the alphabet. | |
return ((col.__len__() - 1) * ((alpha.index(col[0]) + 1) * 26)) + getPosition(col[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment