7
votes

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".

2
I don't think that's possible. You have to make "Blue" active, copy it than activate "Orange" back.Henrique G. Abreu
Do you need to make a "deep copy" or would a value/color copy be sufficient ? In the second case you can achieve it using a getValues/setValues (and equivalent for color, BGcolor etc) schema.Serge insas

2 Answers

12
votes

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');
2
votes

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, .