How to get Column Count of Range

How can I get the number of columns in a given column range? I thought something like this would work, but it doesn’t. I need to use that variable in a loop to process further code. The response in this sample should be “8”.

set columnRange to "A:H"
return count of columns of columnRange

If this is the whole code, your setting columnRange to a string. Not a range.

If it’s not the whole code, more context would be helpful.

This works for me:

tell application "Numbers"
	tell sheet 1 of document 1
		set theRange to range "A:D" of table 1
		log (count of columns of theRange)
	end tell
end tell

Hi pavilion.

  1. A range text has to include the first and last row numbers as well as the first and last column letters. (Edit. I see from testing chrillek’s script above that this isn’t necessarily the case.)
  2. In a Numbers setting, the text has to be preceded by the keyword ‘range’ in order to make a range specifier that Numbers understands:
tell application "Numbers"
	tell table 1 of sheet 1 of document 1
		set theRange to range ("A1:H" & row count)
		return (count theRange's columns)
	end tell
end tell

(The different ‘count’ forms above are due to the fact that tables have row count and column count properties whereas ranges don’t. You actually have to count a range’s rows or columns. A table’s rows and columns can be counted too, so its not clear why tables have specific properties for those values. Maybe it’s for efficiency. :thinking:)

  1. An alternative if you’re starting out with the letters and don’t need to involve the Numbers application at that point might be:
return (id of "H") mod 32 - (id of "A") mod 32 + 1

The two 'mod 32’s make the process effectively case-insensitive, although it only works with single, non-accented letters.

And the range has to be specified “at” a table (for lack of a better term). There’s no range independent of a table (I think). Something like
tell firstTable set myRange to range "A:C"
where firstTable is, for example, defined as
set firstTable to first table of first sheet of first document

The mod 32 is not needed here, since you’re interested only in the difference between the character codes. And that’s the same with or without mod 32. Making the calculation case-insensitive is not necessary, in my opinion, since the last possible one-letter column is “Z” (upper case). Using 2. in your post is seemingly much more robust and flexible.

Hi chrillek.

It’s just a precaution. The ‘id’ of a text is one of the few instances were AppleScript text isn’t treated case-insensitively, leading many scripters not to bother or simply to forget about case in string operations.

return (id of "H") - (id of "a") + 1
--> -24