Home > Software engineering >  Timing out issue in Google Sheet
Timing out issue in Google Sheet

Time:08-05

The code below is used to perform some simple functions in a Google Sheet. It creates two new sheets (makes them (0) and (1), names them, and adds color) and hides another sheet. The code has been extremely unreliable. If I create a blank google sheet and test it works fine but when I add it to the live version of the sheet it times out and fails to run all the code. I also tested copying the live version (in case there was some corruption in the file) and initially it seemed to work but then the same problem occurred. I am brand new to app script so perhaps I am missing something obvious. I would appreciate any suggestions.

function New_Tabs() {
  var spreadsheet = SpreadsheetApp.getActive();
  var curDate = Utilities.formatDate(new Date(), "GMT 1", "M/d") //sets format for current 
  date as month/day

  //Selects and activates the Day_date sheet / Gets calculated date info
  var sheet = SpreadsheetApp.getActive().getSheetByName('Day_Date');
  sheet.activate();
  var val = SpreadsheetApp.getActiveSheet().getRange(2,6).getValue();

  //Logger.log(val) Used this to check the value was pulled correctly

  //Insert the sheet for today's date - Data from portal/Excel macro will be pasted here
  spreadsheet.insertSheet(0); //Makes it the first sheet
  spreadsheet.getActiveSheet().setName(val); //pulls calculated date from Day_Date sheet
  spreadsheet.getActiveSheet().setTabColor('#00ff00'); //Colors the sheet tab green

  //Insert the sheet for Logistics
  spreadsheet.insertSheet(1); //Makes it the second sheet
  spreadsheet.getActiveSheet().setName("Logistics "   curDate ); //names the sheet with text 
  and current date
  spreadsheet.getActiveSheet().setTabColor('#00ff00'); //Colors the sheet tab green


  //trying to slow down to make hiding the tab more reliable
  Utilities.sleep(2000);// pause for 2 seconds


  //selects the sheet for today's date - Data from portal/Excel macro will be pasted here
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName(val), true);

  //trying to slow down to make hiding the tab more reliable
  Utilities.sleep(2000);// pause for 200 milliseconds

  //selects the Day_date sheet and hides it
  spreadsheet.setActiveSheet(spreadsheet.getSheetByName('Day_Date'), true);
  spreadsheet.getActiveSheet().hideSheet();


  SpreadsheetApp.getUi().alert("Completed");

};

CodePudding user response:

Try it this way:

function New_Tabs() {
  const ss = SpreadsheetApp.getActive();
  const curDate = Utilities.formatDate(new Date(), "GMT 1", "M/d");
  const sh = SpreadsheetApp.getActive().getSheetByName('Day_Date');
  const val = sh.getRange(2,6).getValue();
  let ns = ss.insertSheet(0);
  ns.setName(val); 
  ns.setTabColor('#00ff00'); 
  let ns1 = ss.insertSheet(1);
  ns1.setName("Logistics "   curDate ); 
  ns1.setTabColor('#00ff00');
  ns.hideSheet();
  ss.toast("Completed")
}
  • Related