Skip to content

Instantly share code, notes, and snippets.

@jsjoeio
Created July 2, 2021 23:54
Show Gist options
  • Save jsjoeio/f9a68f39fdd2d0a1af35ca9ccce2b85c to your computer and use it in GitHub Desktop.
Save jsjoeio/f9a68f39fdd2d0a1af35ca9ccce2b85c to your computer and use it in GitHub Desktop.
Google Spreadsheet macro example
/** @OnlyCurrentDoc */
const startDate = new Date("2021-06-16")
// so the first one is D2:K2
function MarkEmptyCellsInYesterdayRowWithHyphen() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Group 2 - B");
// Activates the sheet
SpreadsheetApp.setActiveSheet(sheet);
const today = new Date()
const diffInDays = days_between(today, startDate)
// Today, Jul 2 is 17, so tomorrow it will be 18.
// We only want to do it for the day before
// But since the first row in the sheet is the column
// it means July 2 is actually row 18
// Example: Today is July 2nd, 2021.
// There are 17 days between today and the start day
// If we were to run as is and use that number (17) for the row
// it would update 07/01/2021 because that's row 17
// Long story short, this works
const rowForDayBefore = `D${diffInDays}:K${diffInDays}`
const range = sheet.getRange(rowForDayBefore);
sheet.setActiveRange(range);
// Grab current row
const values = range.getValues()
// Update the empty cells with "-"
const updatedValues = updateValues(values)
range.setValues(updatedValues)
};
function updateValues(values) {
// If the value is empty, we mark it with "-"
// It looks like [ [ 'x', 'x', 'x', '', '', 'x', 'x', 'x' ] ]
// which is why we return in array, 2d array
return [values[0].map(v => v === "" ? "-" : v)]
}
// source: https://stackoverflow.com/a/2627482/3015595
function days_between(date1, date2) {
// The number of milliseconds in one day
const ONE_DAY = 1000 * 60 * 60 * 24;
// Calculate the difference in milliseconds
const differenceMs = Math.abs(date1 - date2);
// Convert back to days and return
return Math.round(differenceMs / ONE_DAY);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment