Home » excel » How to loop over selected cells in Excel with Applescript?

How to loop over selected cells in Excel with Applescript?

Posted by: admin May 14, 2020 Leave a comment

Questions:

In VBA I can do something like this to loop through selected cells in Excel:

for each c in Selection
   ' do things
next

I am trying to do the same in AppleScript but I don’t seem to get anywhere. I do get the current cell, but even when I do

set c to count of selection

the result is that c is set to 0.

The Excel applescript manual doesn’t seem to help, nor googling.

Thanks

How to&Answers:

It turns out that you have to use “count large” to get the number of cells in the selection. Once you’ve gotten there, it’s straightforward – like this:

tell application "Microsoft Excel"
    repeat with j from 1 to count large of selection
         -- do stuff with the cell
         set value of cell j of selection to "cell_" & j
    end repeat
end tell

In order to get there I had to do

tell application "Microsoft Excel"
   set c to properties of selection
end tell
return c

and then go through the list of properties until I found a promising one. This was a nice way to get to the property list. Maybe there’s a faster way on the AppleScript editor, but I’m a command line person.

Answer:

You can try something like this:

tell application "Microsoft Excel"
    set range1 to range "A1:A5"
    set value of range1 to {{1.0}, {2.0}, {3.0}, {4.0}, {5.0}}
    set range2 to range "B1:B5"
    set value of range2 to {3}

    repeat with i from 1 to 5
        set formula of row i of column 3 to "=A" & i & "+B" & i
    end repeat
end tell

You can read more here

You can also try:

set cellCount to count of (cells of selection)