保護された範囲やシートの制御
特定のスプレッドシートから、保護された範囲やシートを取得する関数について解説します。
利用する関数
Section titled “利用する関数”Spreadsheet.getProtections(type);Spreadsheet クラスに用意されている、getProtections() を使用します。
引数には保護の種類を表す列挙型 ProtectionType を指定します。範囲の保護を取得する場合は SpreadsheetApp.ProtectionType.RANGE、シートの保護を取得する場合は SpreadsheetApp.ProtectionType.SHEET を指定します。
返り値は、保護された範囲またはシートを表す Protection オブジェクトの配列です。
実行にあたってスプレッドシートにアクセスすることになるため、初回実行時に認証が必要になる場合があります。
サンプルコード
Section titled “サンプルコード”/** * 対象スプレッドシートのID * https://docs.google.com/spreadsheets/d/〇〇〇/edit の〇〇〇の部分 */const SPREAD_SHEET_ID = '_______________';
/** * 保護されている範囲とシートの保護を解除します */const removeProtections = () => { /** 対象スプレッドシート */ const ss = SpreadsheetApp.openById(SPREAD_SHEET_ID);
/** 保護されている範囲 */ const rangeProtections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE); /** 保護されているシート */ const sheetProtections = ss.getProtections(SpreadsheetApp.ProtectionType.SHEET);
// 範囲の保護を解除する for (const protection of rangeProtections) { if (protection.canEdit()) { protection.remove(); } }
// シートの保護を解除する for (const protection of sheetProtections) { if (protection.canEdit()) { protection.remove(); } }};実行すると、指定したスプレッドシートについて、保護されているすべての範囲とシートの保護を解除します。
また、実行ユーザーが保護された範囲やシートの編集権限を持っていない場合は、解除することはできません。サンプルコードでは canEdit() で編集権限を確認し、権限があるものだけを解除しています。