Duplicate worksheet with copy placed next to original

我的梦境 提交于 2021-02-11 18:18:21

问题


I have a script to duplicate a sheet in the same spreadsheet:

function duplicateSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var devis = ss.getActiveSheet();
devis.copyTo(ss).setName('CopyDevis');

It works fine, however the copy tab is created at the very right of the spreadsheet. It is a bit of an issue because i have many tabs and i would have to go to the far right then move it back to the left. I want the copy to created right next to the original.

I'm aware of the moveActivesheet function, but I do not want to use it because it obliges me to make the copy active (setActivesheet) - for some reason i want the process to be done without ever changing the active sheet.

So, i looked into getIndex() (which would tell me the position of the active sheet and create the copy right next to it - but CopyTo doesn't allow this variable (I think).

InsertSheet() wouldn't work because it would make the new sheet active.

Any help would be greatly appreciated.

Thanks


回答1:


Move last sheet one position to the right of the active sheet

On my spreadsheets when I create a duplicate it creates it immediately to the right of the active sheet. But if yours is creating it as the last one on the right end. Then this function will do what you requested.

function moveLastSheetOnePositionToRightOfTheActiveSheet() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var actidx=sh.getIndex();
  var shts=ss.getSheets();
  if(sh) {    
    Sheets.Spreadsheets.batchUpdate(
      {
        requests:[
          {
            "updateSheetProperties": 
            {             
              "properties":
              {
                "sheetId":shts[shts.length-1].getSheetId(),
                "index": actidx
              },
              "fields": "index"                      
            }
          }
        ]
      }, ss.getId());
  }
}


来源:https://stackoverflow.com/questions/56084099/duplicate-worksheet-with-copy-placed-next-to-original

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