Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

javascript - How to sort more then 100 sheets in spreadsheet?

I have google spreadsheet whit more then 100 sheets and i need to sort it by alphabet. Now i have script

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetArray = ss.getSheets();
  var sheetNameArray = [];

  for(var i = 0; i<sheetArray.length; i++){ 
    sheetNameArray.push(sheetArray[i].getSheetName());
  };
 
  sheetNameArray.sort();
  sheetNameArray.forEach(function (element) {
         var sheet = ss.getSheetByName(element);
         ss.setActiveSheet(sheet);
         ss.moveActiveSheet(ss.getNumSheets())
    })

This run in onEdit. But it's work more then 30 seconds and cannot complete. What should i do?

question from:https://stackoverflow.com/questions/65951802/how-to-sort-more-then-100-sheets-in-spreadsheet

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think this would work faster because I tested both codes:

function sortSheets() {   
   const ss = SpreadsheetApp.getActive();
   const allSheets = ss.getSheets();
   const sheetsAr = allSheets.map(sh=>[sh,sh.getName()]);
   sheetsAr.sort((a,b) => a[1].charCodeAt(0)-b[1].charCodeAt(0));
   sheetsAr.forEach((v,i)=>{
                   ss.setActiveSheet(v[0]);
                   ss.moveActiveSheet(i+1);                   
   });
}

You will gain some performance because I got rid of the for loop.

If this does not work, I am afraid you have to use a time-driven trigger which can run from 6 minutes (if you have a consumer account) or 30 minutes (if you have a business account). You can set up the time driven trigger to run every 1 minute or longer so you can have a sort of "live" adjustments in the orders of the sheet.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...