選択したセルを縦方向のみまたは横方向のみ結合する

Numbers上で選択した範囲のセルを、縦方向または横方向に結合するスクリプトです。
矩形状に選択して実行すると横方向か縦方向かを聞いてくるので、選択すると選択範囲内でその方向のみセルが結合されます。
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions

if not (exists front document of application "Numbers") then
beep
display alert "ドキュメントが開かれていません"
return
end if

tell application "Numbers"
tell front document
tell active sheet
try
set theTable to first table whose class of selection range is range
on error
return --何も選択されてなかった場合は終了
end try

tell theTable
set selList to name of (every cell of selection range)

if (length of selList) < 2 then
beep
display alert "セルがひとつしか選択されていません"
return
end if

set selectedButton to button returned of (display alert "選択範囲のセルを結合します。
どちら方向に結合しますか?
(選択範囲が広い場合時間がかかります。しばらくお待ちください。)" buttons {"キャンセル", "縦方向のみ", "横方向のみ"} cancel button "キャンセル" default button "横方向のみ")


set columnCount to count of (column of selection range) --列をカウント
set rowCount to count of (row of selection range) --行をカウント

if selectedButton is "縦方向のみ" then
set startCellList to items 1 thru columnCount of selList
set aList to {}
set bList to {}
repeat with i in startCellList
set topCellStr to my regexReplace((contents of i), "\\d", "")
set topCellNum to my regexReplace((contents of i), "[a-zA-Z]", "")
repeat with ii from 1 to rowCount
set the end of aList to (topCellStr & (topCellNum - 1) + ii)
end repeat
set the end of bList to aList
set aList to {}
end repeat
bList
repeat with j in bList
set aCon to (contents of j)
set aRange to (item 1 of aCon) & ":" & (last item of aCon)
try
merge range aRange
on error msg
beep
display alert msg
return
end try
end repeat
else if selectedButton is "横方向のみ" then
set aList to {}
repeat with i from 1 to rowCount
set the end of aList to items 1 thru columnCount of selList
if (length of selList) > columnCount then
set selList to items (columnCount + 1) thru -1 of selList
end if
end repeat
repeat with ii in aList
set aCon to (contents of ii)
set aRange to (item 1 of aCon) & ":" & (last item of aCon)
try
merge range aRange
on error msg
beep
display alert msg
return
end try
end repeat
end if
end tell
end tell
end tell
end tell


on regexReplace(aText as text, pattern as text, replacement as text)
--require framework: Foundation
set regularExpression to current application's NSRegularExpression's regularExpressionWithPattern:pattern options:0 |error|:(missing value)
return (regularExpression's stringByReplacingMatchesInString:aText options:0 range:{location:0, |length|:count aText} withTemplate:replacement) as text
end regexReplace

動作状況です。

更新履歴

inserted by FC2 system