Skip to content

Instantly share code, notes, and snippets.

@aberonni
Created March 24, 2021 09:20
Show Gist options
  • Save aberonni/e43ec5bb860fa96be632409b1a265faa to your computer and use it in GitHub Desktop.
Save aberonni/e43ec5bb860fa96be632409b1a265faa to your computer and use it in GitHub Desktop.
/**
* This function is set to run on a daily trigger so that
* there is no need for manual intervention on the sheet.
*
* The trigger was set up following this guide:
* https://www.quora.com/How-can-I-periodically-run-a-Google-Script-on-a-Spreadsheet
*
* You should be able to add this script to a new google sheet that uses
* the same format by doing the following
* - open the spreadsheet you want to add this script to
* - go the Tools > Script editor...
* - Copy-paste this code into a new file
* - Edit the values of the UPPERCASE constants at the top of the file
* - Setup a trigger to run the "updateSheet" function daily
*/
// The sheet we want to update
const SHEET_NAME = "Quantitative";
// The row that will contain the most recent data
const LATEST_ROW = 4;
// The column that contains the date (or week) information
const DATE_COLUMN = "A";
function updateSheet() {
const sheet = SpreadsheetApp
.getActiveSpreadsheet()
.getSheetByName(SHEET_NAME);
// Store the value of the date column for the latest row
const latestWeek = new Date(sheet
.getRange(`${DATE_COLUMN}${LATEST_ROW}`)
.getValue());
const now = new Date();
// Only update the sheet if the latest row's date cell is in the past
const shouldUpdate = latestWeek < now;
if (!shouldUpdate) {
return;
}
// Insert a blank row before the latest row
sheet.insertRowsBefore(LATEST_ROW, 1);
// The range represents the latest row from the first to last column.
const lastColumn = sheet.getLastColumn();
const range = sheet.getRange(LATEST_ROW + 1, 1, 1, lastColumn);
// Copy the latest row to the row we just added
// When contentsOnly is true, a "paste values" occurs. We want the functions, so it's set to false.
range.copyTo(sheet.getRange(LATEST_ROW, 1, 1, lastColumn), {contentsOnly:false});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment