问题
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