Exception Error with Google Script when I tried to use moveActiveSheet

前提是你 提交于 2021-01-07 01:04:44

问题


I keep getting "Exception: Service Spreadsheets failed while accessing document with id " while trying to run moveActiveSheet to move a sheet in tab with index 4 to index 1. This just happened very lately. I had been using my code for months before this happened. Does any body is facing the same thing?

My code is below

var ss = SpreadsheetApp.getActiveSpreadsheet();
//==========================================
//Arrange the Sheet
// Store all the worksheets in this array
var sheetNameArray = [];
var sheets = ss.getSheets();
for (var i = 0; i < sheets.length; i++) {
    sheetNameArray.push(sheets[i].getName());
};
sheetNameArray.sort();

var sheetName = sheetNameArray[0]; //This tab is currently at index 4
var getSheet = ss.getSheetByName(sheetName);
Logger.log(getSheet.getIndex());
ss.setActiveSheet(getSheet);
ss.moveActiveSheet(1); //Trying to move it to index 1 but exception was thrown

回答1:


Here is a work-around that worked for me, I loop through the sorted array. I used .batchUpdate from Sheets API. You have to enable it from advanced services first: Resources > Advanced Google Services

function move_sheet_func(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  //==========================================
  //Arrange the Sheet
  // Store all the worksheets in this array
  var sheetNameArray = [];
  var sheets = ss.getSheets();
  for (var i = 0; i < sheets.length; i++) {
    sheetNameArray.push(sheets[i].getName());
  };
  sheetNameArray.sort();
  
  var sheetName = sheetNameArray[0]; //This tab is currently at index 4
  var getSheet = ss.getSheetByName(sheetName);
  var sheetsreq = [];
  //create requests for each sheet to be moved to its index as sorted
  sheetNameArray.forEach(function (name, indx) {
    sheetsreq.push({ updateSheetProperties: {
      fields: "index, title",
      properties: {
        index: indx,
        title: name,
        sheetId: ss.getSheetByName(name).getSheetId()
      }
    } });
  });
  var req = { "requests": sheetsreq };
  console.log(JSON.stringify(req));
  Sheets.Spreadsheets.batchUpdate(req, ss.getId());

}


来源:https://stackoverflow.com/questions/65313042/exception-error-with-google-script-when-i-tried-to-use-moveactivesheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!