LoginSignup
0
1

More than 1 year has passed since last update.

エクセルで範囲指定したセルの値を返す AppleScript

Last updated at Posted at 2023-02-21

作成した動機

例えばこのようなエクセルがあったとして、各セルの数値を合計した値を知りたいといった場合、
いちいち計算式書くの面倒なのでAppleScriptを書いてみました。
スクリーンショット 2023-02-21 14.45.52.png

調べながら、前進

エクセルの範囲指定された領域を取得するには、以下のスクリプトでできました。

sample01.scpt
tell application "Microsoft Excel"
	get selection
end tell

get selection で返ってくるのは range オブジェクトです。

sample02.scpt
tell application "Microsoft Excel"
	set myRange to get selection
	class of myRange
end tell
結果.txt
range

この状態では各セルの値が取れそうもないので、スクリプトエディタ.appでエクセルの用語説明を見てみます。
スクリーンショット 2023-02-21 14.56.35.png
renge の arias プロパティがそれっぽいですね。
スクリーンショット 2023-02-21 14.56.05.png

areas (list of specifier, r/o) : Returns a list of range objects that represents all the ranges in a multiple-area selection.

DeepLで翻訳してみると

areas (list of specifier, r/o) : 複数領域選択におけるすべての領域を表す範囲オブジェクトのリストを返す。

renge の arias プロパティを見てみましょう

sample3.scpt
tell application "Microsoft Excel"
	set myRange to get selection
	--class of myRange --> range object
	areas of myRange
end tell
結果.txt
{range "[Book1]Sheet1!$A$1:$C$3" of application "Microsoft Excel"}

返ってきた値には、範囲指定されたセルのアドレスが入っていました。
なので、これでどうなるか……試してみます

sample4.scpt
tell application "Microsoft Excel"
	set myRange to get selection
	value of areas of myRange
end tell
結果.txt
{{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}}

各セルの値がリストで取得できました。

範囲指定したセルの数字の合計を求める

これまでの成果をハンドラにし、合計を求めます。

ExTotal.scpt
set myList to getVals()

set total to 0
repeat with r from 1 to number of myList
	set myRow to item r of myList
	repeat with c from 1 to number of myRow
		set myVal to item c of myRow
		set total to total + myVal
	end repeat
end repeat
total

on getVals()
	tell application "Microsoft Excel"
		set myRange to get selection -- range obj
		tell myRange
			value of areas
		end tell
	end tell
end getVals
結果.txt
45.0

何かの参考になれば、幸いです。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1