user2912312
user2912312

Reputation: 155

How to copy one google sheet to different another google sheet

I do have two different google sheet, I need to copy say sheet Test from one to another using script, but getting error, any thought on this?

   var source_sheet= "https://address of the otgoogle sheet tho be copied over")"

  //here I'm on another google sheet, add a menu to copy the source from above
  var ui = SpreadsheetApp.getUi(); 
 //var ss = SpreadsheetApp.getActiveSpreadsheet();  
  var result = ui.prompt(      
  'Add New Sheet',
  'Please enter Name',
  ui.ButtonSet.OK);         

  var button = result.getSelectedButton();
  var text = result.getResponseText();

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();

  sheet.copyTo(link_to_src).setName(text);

Getting below error: Exception: The parameters (String) don't match the method signature for SpreadsheetApp.Sheet.copyTo. (line xx, file "copy-rename")DetailsDismiss

Any help will be appreciated in advance..

Upvotes: 2

Views: 985

Answers (1)

Tanaike
Tanaike

Reputation: 201378

  • You want to copy a sheet of the source Spreadsheet, which is not the active Spreadsheet to the active Spreadsheet, which run the script.
  • source_sheet is the URL of Spreadsheet like https://docs.google.com/spreadsheets/d/{spreadsheetId}/edit.
  • When you run the script, you want to input the sheet name in source Spreadsheet using a dialog and copy the sheet to the active Spreadsheet.

I could understand like above. If my understanding is correct, how about this modification?

Modified script

Please modify your script as follows. Before you run the script, please set the destination Spreadsheet URL to source_sheet.

From:
var sheet = ss.getActiveSheet();
sheet.copyTo(link_to_src).setName(text);
To:
var sourceSheet = SpreadsheetApp.openByUrl(source_sheet).getSheetByName(text);
if (sourceSheet) {
  sourceSheet.copyTo(ss).setName(text).activate();
} else {
  ui.alert(text + " sheet was not found.");
}
  • When you run the script, a dialog is opened. When a sheet name of the source Spreadsheet is inputted, the sheet is copied to the current active Spreadsheet, then, the copied sheet is activated.
  • If the sheet name which is not included in the source Spreadsheet is inputted, a dialog is opened.

References:

Upvotes: 4

Related Questions