2月 24, 2012
inomoto

【Excel2008】スクリプト2件ご紹介

今回はExcel用のAppleScript2件です.

お客様からいただいたCSVやTSVを加工して色々する作業が多いのですが,もとの値がどうなっていたかを確認するために,それらをExcelで開いて確認することが多いです.
そのとき,それぞれの列に適した列幅を設定したり,オートフィルタで整理した状態にしたりと色々するのですが,ファイルが多いとそれも大変です.

1 コラム幅を設定し,適用する
setWidthPrefList内に入力した設定の通りに,列幅を変更します.
setWidthPrefList内のリストは,列のインデックスも合わせて入力する仕様なので,順番通りでなくても大丈夫です.

サンプルでは,
・1〜4列目はオートフィット
・5列目は100
・6列目は設定なし
となっています.

[applescript]
tell application "Microsoft Excel"
tell active workbook
set widthPrefList to setWidthPrefList() of me –コラム幅設定用のリストを作成
setColumnWidth(widthPrefList) of me –設定リストに従いコラム幅を設定

end tell
end tell

–設定リストに従いコラム幅を設定
on setColumnWidth(widthPrefList)
set aConstant to 2.5142281 –変換用定数
tell application "Microsoft Excel"
tell active workbook
tell active sheet
repeat with aData in widthPrefList
set {aNum, aWidth} to aData
tell column aNum
if aWidth is "auto" then
autofit
else
set aWidth to aWidth / aConstant
set column width to aWidth
end if
end tell
end repeat
end tell
end tell
end tell
end setColumnWidth

–コラム幅設定用のリストを作成
on setWidthPrefList()
set widthPrefList to {} –定義

(*{インデックス, 幅}で設定,"auto"でautofit.数字はダイアログに入力する数字*)
set the end of widthPrefList to {1, "auto"}
set the end of widthPrefList to {2, "auto"}
set the end of widthPrefList to {3, "auto"}
set the end of widthPrefList to {4, "auto"}
set the end of widthPrefList to {5, 100}

return widthPrefList
end setWidthPrefList

[/applescript]

この状態が

こうなります.

2 オートフィルタを設定する

シートにオートフィルタを設定し,指定の列の指定の値でフィルタをかけます.

サンプルでは,2列目を「野菜」でフィルタしています.

[applescript]
tell application "Microsoft Excel"
tell active workbook
tell active sheet
setAutofilter() of me
setCriteria(2, "野菜") of me –オートフィルタのフィルタ内容を変更

end tell
end tell
end tell

–オートフィルタのフィルタ内容を変更
on setCriteria(aNum, c1)
tell application "Microsoft Excel"
tell active workbook
tell active sheet
tell used range
if c1 is not "" then
autofilter range field aNum criteria1 c1
else
autofilter range field aNum –第2パラメータが空なら全てを表示
end if
end tell
end tell
end tell
end tell
end setCriteria

–used rangeにオートフィルタを設定
on setAutofilter()
tell application "Microsoft Excel"
tell active workbook
tell active sheet
set enable autofilter to true
tell used range
autofilter range
end tell
end tell
end tell
end tell
end setAutofilter
[/applescript]

この状態が

こうなります.

Leave a comment