Copying a Sheet to a Specific Spreadsheet in Apps Script
This post is a corrected post after AI explains the code included in the book “Google Apps Script 101: Building Work Automation For Free”. Added a strikethrough when editing what AI has written, and added color when edited by author
Table of Contents
Summary
In this blog post, we will explore how to copy a sheet to a specific spreadsheet using Apps Script. We will learn how to retrieve the active spreadsheet, get a specific sheet by name, open a specific spreadsheet by its ID, and copy the sheet to the target spreadsheet.
Code
1 2 3 4 5 6 7 |
function copyTabToSpecificSheet() { const SS = SpreadsheetApp.getActiveSpreadsheet(); const T_SHEET2 = SS.getSheetByName('Sheet2'); const SS_byId = SpreadsheetApp.openById('ID'); T_SHEET2.copyTo(SS_byId); } |
Code Explanation
The code defines a function named copyTabToSpecificSheet
. Inside the function, it retrieves the active spreadsheet using SpreadsheetApp.getActiveSpreadsheet()
. It then gets a specific sheet named “Sheet2” using getSheetByName()
method and assigns it to the T_SHEET2
variable.
The function also opens a specific spreadsheet using its ID with SpreadsheetApp.openById()
and assigns it to the SS_byId
variable.
Finally, it copies the T_SHEET2
sheet to the target spreadsheet using the copyTo()
method.
Example
Let’s say we have a master spreadsheet with multiple sheets, and we want to copy the “Sales” sheet to another spreadsheet named “Sales Reports”. We can use the following code:
1 2 3 4 5 6 7 |
function copySalesSheetToReports() { const masterSS = SpreadsheetApp.getActiveSpreadsheet(); const salesSheet = masterSS.getSheetByName('Sales'); const reportsSS = SpreadsheetApp.openById('SalesReportsID'); salesSheet.copyTo(reportsSS); } |
This code retrieves the active spreadsheet, gets the “Sales” sheet, opens the “Sales Reports” spreadsheet by its ID, and copies the “Sales” sheet to the “Sales Reports” spreadsheet.
AI Prompt
Write a function that copies a specific sheet to a target spreadsheet. Retrieve the active spreadsheet, get the desired sheet by name, open the target spreadsheet by its ID, and copy the sheet to the target spreadsheet.