★うめじ英語塾 お問い合わせフォーム★

Google Drive上の指定したフォルダにあるフォームの一定期間過ぎた回答を削除するGASコード

Google Drive上の指定したフォルダにあるフォームの一定期間過ぎた回答を削除するGASコード
Summary

The following Google Apps Script (GAS) code allows you to set an expiration time and selectively delete all the expired form responses in a specified folder on Google Drive.

Warning: with this code, all the form responses that are deleted will be deleted forever and can no longer be accessed. The deletion is irreversible.

先日(2022年6月12日)、Google Drive 上の指定したフォルダにあるフォームの回答に保管期間を設定し、保管期間が過ぎた全ての回答を削除するプログラムを書きました。誰かのお役に立てるのではないかと思い、まとめてみました。なお、このプログラムは「暫定ざんてい版」です。問題点の指摘をお願いします。

Google Drive上の 1234567890_abcdefghijklmnopqrstuvwxzy という ID のフォルダにある全てのフォームの90日間の保管期間が過ぎた回答を削除したい場合の例をお示しします。

function DeleteOldResponses() {
  let id = "1234567890_abcdefghijklmnopqrstuvwxzy";
  let folder = DriveApp.getFolderById(id);
  let files = folder.getFiles();
  let currentTime = new Date().valueOf(); //今日の日付 Today’s Date 
  let expirationTime = currentTime - 90*24*3600*1000;
  //必要に応じて変更。この例では、90は保管日数。24*3600*1000 は1000分の1秒単位で1日。
  //Change to suit your needs. In this example, 90 is the number of days elapsed. 24*3600*1000 is one day in milliseconds.
  while (files.hasNext()) {
    let file = files.next();
    let mimeType = file.getMimeType();
    //Googleフォームだけを抽出して処理 Extract and process only Google Forms.
    if (mimeType == 'application/vnd.google-apps.form') {
      let id2 = file.getId();
      let form = FormApp.openById(id2);
      let formResponses = form.getResponses();
      for (let i = 0; i < formResponses.length; i++) {
        let formResponse = formResponses[i];
        let responseTime = formResponse.getTimestamp().valueOf();
        if (responseTime < expirationTime) {
          let id3 = formResponse.getId();
          form.deleteResponse(id3);
        }
      }
    }
  }
}

なお、このプログラムを使うためには、Google にログインして、My Projects(自分のプロジェクト)にアクセスし、新しいプロジェクトを作り、実行時のアクセス許可の承認等の手順を踏む必要があります。詳細はネット検索していただけたらと思います。

注意!
このプログラムを使ってフォームから削除した回答は、「元に戻す」でも復元できません。

ただし、フォームの回答を事前にスプレッドシートに保存した場合、フォームの回答を削除しても、スプレッドシートに保存されている回答は削除されません。
関連ウェブページ:フォームの回答の保存先を選択する – Google ドキュメント エディタ ヘルプ


【参考にした動画やウェブサイト】

  1. Free GAS script : Delete entries from your form after a given time
  2. Google DriveApp Example Google Apps Script List Files in Folder from Drive – YouTube
  3. Google Apps Script Deleting Google Drive Files in Folder Example – YouTube
  4. Class FormResponse | Apps Script | Google Developers