[Solved] Is there a code for Google Sheets that will move every tab of a specific color to the end of my list of tabs?


Moving sheets/tabs of a color to end of list of tabs using Google Sheets API version 4

function moveSheetsOfAColorToEnd(color) {
  var color=color || '#ff0000';
  if(color) {
    var ss=SpreadsheetApp.getActive();
    var shts=ss.getSheets();
    for(var i=0;i<shts.length;i++) {
      if(shts[i].getTabColor()==color) {            
        Sheets.Spreadsheets.batchUpdate(
          {
            requests:[
              {
                "updateSheetProperties": 
                {             
                  "properties":
                  {
                    "sheetId":shts[i].getSheetId(),
                    "index": shts.length
                  },
                  "fields": "index"                      
                }
              }
            ]
          }, ss.getId());
      }
    }
  }
}

You will need to Enable Sheets API v4 in Resources Menu and also in the Google Cloud Platform.

Google Sheets API v4 Reference

This question helped me a lot.

shts.length is the length of the array returned from Spreadsheet.getSheets(). Since the sheets index begins at one setting a given sheet index to the length of that array will always move that sheet to the end.

Here’s another way to do the same thing:

function moveSheetsOfAColorToEnd1(color) {
  var color=color || '#ff0000';
  if(color) {
    var ss=SpreadsheetApp.getActive();
    var shts=ss.getSheets();
    for(var i=0;i<shts.length;i++) {
      if(shts[i].getTabColor()==color) {
        var shtsPropReq=Sheets.newUpdateSheetPropertiesRequest();
        shtsPropReq.properties=Sheets.newSheetProperties();
        shtsPropReq.properties.sheetId=shts[i].getSheetId();
        shtsPropReq.properties.index=shts.length;
        shtsPropReq.fields="index";
        var requests=[Sheets.newRequest()];
        requests[0].updateSheetProperties=shtsPropReq;
        var batchUpdateRequest=Sheets.newBatchUpdateSpreadsheetRequest();
        batchUpdateRequest.requests=requests;
        Sheets.Spreadsheets.batchUpdate(batchUpdateRequest, ss.getId());
      }
    }
  }
}

This method follows the same pattern as the Apps Script example found on this page.

There are some additional examples found here

5

solved Is there a code for Google Sheets that will move every tab of a specific color to the end of my list of tabs?