1
votes

I am trying to create a simple script with a function to create new sheets and a main function to email those sheets. When I try to call the function to create sheets inside the main function, it emails empty sheets. Here is a sample of what I am doing:

function createnewsheets(mainfile, newsheetname) {
  mainfile.insertSheet(newsheetname);
  var sheet = mainfile.getSheetByName(newsheetname);
  var cell = sheet.getRange("A1");
  cell.setValue("Hello");
  return sheet;   
}
function doall(){
  var mainfile = SpreadsheetApp.openByUrl('https://docs.google.com/...');
  var sheet = createnewsheets(mainfile, "random");
  ////code to send sheet as attachment in email///
}

Full code is here.

Now this sends empty sheet, but if first execute createnewsheets without returning and fetch the sheet with the name in doeverything, it does work.

I thought it might be an issue of wait after creating a sheet, so I also tried Utilities.sleep() but that didn't change anything.

It would be very helpful to know how can I improve. Thanks in advance.

1
Apologies, I meant Utilities.sleep() instead of wait. ThanksWiData

1 Answers

2
votes

Google Apps Script apply changes made on Google Sheet in batches:

Scripts commonly need to read in data from a spreadsheet, perform calculations, and then write out the results of the data to a spreadsheet. Google Apps Script already has some built-in optimization, such as using look-ahead caching to retrieve what a script is likely to get and write caching to save what is likely to be set.

Use SpreadsheetApp.flush() to "force" the application of the changes that your script made before sending the sheets by email.

Related