Skip to content

Instantly share code, notes, and snippets.

@fmarais
Created May 3, 2020 12:16
Show Gist options
  • Save fmarais/4f4eb525543b0607be226639fc53f5ab to your computer and use it in GitHub Desktop.
Save fmarais/4f4eb525543b0607be226639fc53f5ab to your computer and use it in GitHub Desktop.
This script will automatically save spreadsheet sheets when edited in Google docs.
function myOnEdit() {
var fileId = "1Ly5SSIE9d-b_IA6VxDB1HF3pnf37SPf22KhZVv3PPiVA1w";
var folderId = "1S1F8NpjOfbxY_4n27llfqh6eOs3Kb1eojaq";
var file = DriveApp.getFileById(fileId);
var folder = DriveApp.getFolderById(folderId);
var now = new Date();
var fileNameDate = now.getFullYear() + "-" + zeroPrefix_(now.getMonth()+1) + "-" + zeroPrefix_(now.getDate()) + 'T' + zeroPrefix_(now.getHours()) + ":" + zeroPrefix_(now.getMinutes()) + ":" + zeroPrefix_(now.getSeconds())
// backup file
if (file && folder) {
var filename = file.getName() + " - " + fileNameDate;
file.makeCopy(filename, folder)
}
}
function zeroPrefix_(s) {
return ('0' + s).slice(-2);
}
This script will automatically save spreadsheet sheets when edited in Google docs.
Installation:
* Open your google spreadsheet
* Open the script editor by clicking on Tools -> Script Editor
* Paste this code into the script editor
* Change the fileId to file you want to backup,
eg. https://docs.google.com/spreadsheets/d/1Ly5SSIE9d-b_IA6VxDB1HF3pnf37SPf22KhZVv3PPiVA1w/edit#gid=966474823
the fileId would be:
1Ly5SSIE9d-b_IA6VxDB1HF3pnf37SPf22KhZVv3PPiVA1w
* Change the folderId to the folder you want to save the backups in,
eg. https://drive.google.com/drive/folders/1S1F8NpjOfbxY_4n27llfqh6eOs3Kb1eojaq
the folderId would be:
1S1F8NpjOfbxY_4n27llfqh6eOs3Kb1eojaq
* Select Resources -> Current project's triggers
* Click "Add a new trigger"
* Under the "Run" column select "myOnEdit" and under the "Events" column select "From spreadsheet" and "On edit"
* Click "Save" to close the triggers dialog
* Select File->Save to save the script
@shurtador
Copy link

Great code! Super simple when there are tons of other alternatives that really do the same but with twice the number of lines!
Very useful. Thank you so much for your contribution

@sup-fmarais
Copy link

Great code! Super simple when there are tons of other alternatives that really do the same but with twice the number of lines!
Very useful. Thank you so much for your contribution

Thanks for the feedback! Appreciated

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment