Home > database >  What reference to the sheet I should use in google app script?
What reference to the sheet I should use in google app script?

Time:12-28

I have a function in the .gs file:

function DayMacros() {
  var spreadsheet = SpreadsheetApp.openById("<some_id>");
  var sheet = spreadsheet.getSheetByName('<sheet_name>');
  var lastrow = sheet.getLastRow();
  var source = sheet.getRange('A'  lastrow  ':G'  lastrow)
  source.autoFill(sheet.getRange('A'  lastrow  ':G'  (lastrow   1)), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
};

The purpose of this function is to add 1 row to the table. And I have a trigger that invokes this function every day. My question is: "Is this the right way to reference the sheet?". Maybe I can get it somehow in function because it is recorded as a macro for the sheet. I tried to use the .getActive() method of SpreadsheetApp, but it occurred that when the trigger works, no spreadsheet is activated, so it simply returns NULL.

CodePudding user response:

In your code:

This SpreadsheetApp.openById("<some_id>"); returns an object of Class Spreadsheet and this sheet.getSheetByName('<sheet_name>') returns an object of Class Sheet.

CodePudding user response:

Since the script is bounded to a Google Spreadsheet, then you can use the following:

function DayMacros() {
  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getSheetByName('<sheet_name>');
  var lastrow = sheet.getLastRow();
  var source = sheet.getRange('A'  lastrow  ':G'  lastrow)
  source.autoFill(sheet.getRange('A'  lastrow  ':G'  (lastrow   1)), SpreadsheetApp.AutoFillSeries.DEFAULT_SERIES);
};

If you're working with a different Google Spreadsheet or with a standalone script, then you can use the script you posted in your question.

References:

getActive()

openById(id)

  • Related