ぼんやりDTP

DTPに関係したりしなかったりするぼんやりとした話をなんとなく。

Excel のシートを AppleScript で削除する

Excel のワークブックの大量のシートをざっくり削除したい。

Excel のシートを先頭から入力した数までのシートを残して、最後のシートまで削除する AppleScript のサンプルコード

display dialog "Please input max number of sheets to leave." default answer 1
set theValue to text returned of result as number

tell application "Microsoft Excel"
    set theWorkbook to active workbook
    set maxNumber to theValue
    set currentSheetNumber to count of sheet of theWorkbook
    set display alerts to false --削除の際の確認アラートを出さない
    repeat until currentSheetNumber ≤ maxNumber
        delete sheet currentSheetNumber of theWorkbook
        set currentSheetNumber to currentSheetNumber - 1
    end repeat
    set display alerts to true
end tell

beep

Excel のアクティブなシートを残して、他のシートを削除する AppleScript のサンプルコード

tell application "Microsoft Excel"
    set theWorkbook to active workbook
    set theSheet to active sheet
    set theIndex to entry_index of theSheet
    set currentSheetsNumber to count of sheet of theWorkbook
    set display alerts to false --削除の際の確認アラートを出さない
    set currentSheetNumber to currentSheetsNumber
    
    repeat until currentSheetNumber = 0
        set currentSheet to sheet currentSheetNumber of theWorkbook
        if currentSheetNumber is not theIndex then
            delete sheet currentSheetNumber of theWorkbook
        end if
        set currentSheetNumber to currentSheetNumber - 1
    end repeat
    set display alerts to true
end tell

beep