Created
January 17, 2021 01:10
-
-
Save lorenzodifuccia/9b15e0973105a79edaeba71da51a9571 to your computer and use it in GitHub Desktop.
Daily Activities Sheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var FIRST_ROWS = 100; | |
var NON_WORKING_DAYS_BG = "#d9d9d9"; | |
function onOpen(e) { | |
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); | |
/* | |
First row is the header. | |
The cell A2 has the first day from which start the timesheet. | |
*/ | |
var firstCell = sheet.getRange(2, 1); | |
if (firstCell.getValue() === "" || (typeof firstCell.getValue() === "string" && firstCell.getValue().contains("START DATE"))) { | |
firstCell.setValue("Please set HERE the START DATE..."); | |
return true | |
} | |
var dateFormat = firstCell.getNumberFormat(); | |
var startDate = new Date(firstCell.getValue()); | |
var todayDate = new Date(); | |
var timeDiff = Math.abs(todayDate.getTime() - startDate.getTime()); | |
var daysBetween = Math.ceil(timeDiff / (1000 * 3600 * 24)); | |
if (checkFirstDisplay(sheet)) { | |
for (var i = 1; i < ((daysBetween < FIRST_ROWS) ? daysBetween : FIRST_ROWS); i++) { | |
addRow(sheet, 2 + i, i, startDate, dateFormat) // `row` here is `1 + i` because of the header. | |
} | |
} | |
var currentCell = sheet.getRange(daysBetween + 1, 1); // Add the header row. | |
sheet.setCurrentCell(currentCell); | |
if (!checkDateDisplay(sheet, daysBetween + 30)) { | |
for (var i = 1; i < daysBetween + 30; i++) { | |
addRow(sheet, 2 + i, i, startDate, dateFormat) | |
} | |
sheet.setCurrentCell(currentCell); | |
} | |
} | |
function checkFirstDisplay(sheet) { | |
// This fuction return `true` if the timesheet is not set, otherwise `false`. | |
return (sheet.getRange(3, 1).getValue() === "") ? true : false | |
} | |
function checkDateDisplay(sheet, days) { | |
// This function return `true` if there are displayed enough cells after the current one, otherwise `false`. | |
for (var i = 3; i < days; i++) { | |
if (sheet.getRange(i, 1).getValue() === "") return false | |
} | |
return true | |
} | |
function addRow(sheet, row, index, startDate, dateFormat) { | |
var cell = sheet.getRange(row, 1); | |
cell.setNumberFormat(dateFormat); | |
var date = new Date(startDate.valueOf() + (index * 1000 * 3600 * 24)); | |
if (date.getUTCDay() === 5 || date.getUTCDay() === 6) sheet.getRange(row, 1, 1, sheet.getMaxColumns()).setBackground(NON_WORKING_DAYS_BG); | |
cell.setValue(Utilities.formatDate(date, "GMT+2", "dd/MM/yyyy")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Moved to Gist from an old repo.
Daily Activities Sheets
Create a Google Sheets like this:
Load the script, set the START DATE and let the script works: