Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Script to Duplicate Sheet that is Not Active

In Google spreadsheets, i would like to perform a simple copy/rename of an existing spreadsheet in a workbook using a script. All the examples i have found online are copying from the active spreadsheet. Can you not perform the below task without first activating/selecting the spreadsheet i want to duplicate?

Example: My workbook contains the following sheet names: "Orange", "Blue"

I want to make a copy of "Blue" and rename it to "Red". So i am left with now 3 sheets "Orange", "Blue", "Red" all while keeping my active spreadsheet on "Orange".

like image 218
PY_ Avatar asked Mar 20 '14 12:03

PY_


2 Answers

You can use the copyTo() method to copy a sheet into the same spreadsheet, it creates a copy!

 var source = SpreadsheetApp.getActiveSpreadsheet();
 var sheet = source.getSheetByName('Blue');

 sheet.copyTo(source).setName('Red');
like image 58
JDuarteDJ Avatar answered Oct 28 '22 13:10

JDuarteDJ


Yes you can. Look at sheet's getSheetByName. If for some reason the api does need the sheet copied to be active (doubt it), simply call setActiveSheet on it before, .

like image 21
Zig Mandel Avatar answered Oct 28 '22 13:10

Zig Mandel