Home > database >  Google App Script - Script to write in cells according to the day of the week
Google App Script - Script to write in cells according to the day of the week

Time:02-20

I'm trying to add this section to my Google app script. I want to add a script that changes the cell to write into, according to the day of the week. For example:

If day=monday then write in cell S1
If day=tuesday then write in cell T1
If day=wednsday then write in cell U1

ecc.

Do you know how can i achieve this result? Thanks!

CodePudding user response:

In Javascript, you can get the day of the week (numeric index) using new Date().getDay() method. The next part is to get a reference to the target cell on the spreadsheet using sheet.getRange() method.

I would recommend to go through the following resources to understand how the solution works:

  1. getDay() on MDN
  2. getRange()
  3. setValue()

Solution:

The following code will,

  • On Sunday, write the string "test" to cell S1,
  • On Monday, write the string "test" to cell S2 and so on.
const spreadsheetId = "...";
const sheetName = "Sheet1";
const spreadsheet = SpreadsheetApp.openById(spreadsheetId);
const sheet = spreadsheet.getSheetByName(sheetName);
const today = new Date().getDay();
const cell = sheet.getRange(`S${today 1}`)
cell.setValue("test");

If you want to skip Sunday and write to S1 on Monday, you need to modify it

if (today > 0) {
  const cell = sheet.getRange(`S${today}`)
  cell.setValue("test");
}

CodePudding user response:

Use getDay() method of Date() object like this:

sheet.getRange(1, new Date().getDay()   19).setValue()
  • Related