Search code examples
google-apps-scriptgoogle-sheetsgoogle-drive-api

Active or not active sheet? how to write to non-active sheet


I have a script that reads through google drive folders and gives me a summery in google sheets. The write part of it uses getActive sheet. It takes a couple of minutes to excecute depending on how many files there are. I want to run the script every hour, so the the sheet will alway up to date with file deliveries. it works fine during the day where the sheet is active. But i got an error message list form google with failed atempts during the night where the sheet was not active, and i could therfore not use the active sheets command. Question is hiw to write to a sheet that is not active, if it is possible?

Cheers Mads

Ok figured it out: First i need to open the SpreadSheet (on the serner), thin get the sheet and then write to it: Final function is somthing like this:

function writeToClosedSheet(){ var ss = SpreadsheetApp.openByUrl("url_to_Sheet") var sheet = ss.getSheetByName('NameOfSheet'); sheet.appendRow( ["Mads found a solution"]); }

This works :)


Solution

  • replace .getActiveSheet() by .getSheetByName('mySheetName')

    if the script is not bound to the spreadsheet, you have to call the spreadsheet by openbyid like const sheet = SpreadsheetApp.openById('SPREADSHEET_ID').getSheetByName('SHEET_NAME')