2016-01-28T10:10:27+09:00

Excel のチャートに名前を設定して、それをファイル名としてチャートを保存する AppleScript

Excel 2008 for mac のチャートに対してコンテキストメニューから「図として保存...」を実行すると、ファイル保存ダイアログが開かれます。なぜか、ファイル保存ダイアログのデフォルトの場所が常に「ピクチャ」フォルダになっている。いったい、どんな気の利かせ方をしたらこうなるのだろう。

僕としては、

  1. Excel ワークブックがある場所に、
  2. PDF ファイルとして、
  3. チャートの名前から、ファイル名を決定して、

保存したい。

たぶん、あまり知られていないのではないかと思いますが、Excel のチャート(グラフ)には、名前が設定できます。Windows の Excel では、名前を設定するインターフェースがちゃんと用意されているようですが、Excel 2008 for Mac では AppleScript からしか設定できないもよう。新しい 2011 とか 2016 ではどうなっているのだろう。

このチャートの名前を設定して、チャート名をファイル名としてチャートを保存する AppleScript を作りました。スクリプトメニュー等から実行してください。

なお、コンパイルに ModuleLoader, XFile, PathInfo のインストールが必要です。

property XFile : module
property _ : boot (module loader) for me

on run
try
main()
on error msg number errno
if errno is not -128 then
activate
display alert msg message "Error Number : " & errno
end if
end try
end run

on active_chart_name()
tell application id "com.microsoft.Excel"
set a_chartname to name of active chart
if a_chartname is missing value then
return missing value
end if
set a_sheetname to name of active sheet
return text ((length of a_sheetname) + 2) thru -1 of a_chartname
end tell
end active_chart_name

on confirm_chart_name(a_chartname)
activate
set a_result to display dialog "Enter chart name :" default answer a_chartname
set a_newname to text returned of a_result
if a_newname is not a_chartname then
tell application id "com.microsoft.Excel"
set name of chart object a_chartname of active sheet to a_newname
end tell
end if
return a_newname
end confirm_chart_name

on main()
set a_chartname to active_chart_name()

if a_chartname is missing value then
display alert "No active chart."
return
end if

set a_chartname to confirm_chart_name(a_chartname)

tell application id "com.microsoft.Excel"
set wbpath to path of active workbook
end tell

set a_path to wbpath & ":" & a_chartname & ".pdf"
set x_chartfile to XFile's make_with(a_path)
if (x_chartfile's item_exists()) then
activate
set a_path to choose file name with prompt ¬
"Choose an output file" default name x_chartfile's item_name() ¬
default location x_chartfile's parent_folder()'s as_alias()
set x_chartfile to XFile's make_with(a_path)
if x_chartfile's item_exists() then
x_chartfile's remove()
end if
set a_path to a_path as text
end if

tell application id "com.microsoft.Excel"
save as picture (chart object a_chartname of active sheet) ¬
picture type save as PDF file ¬
file name a_path
end tell

activate
display alert "PDF Exported in : " & return & a_path
end main