Copying Data Between Sheets 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 data between sheets in Apps Script. We will learn how to use the copyTo
method to copy the data range from one sheet to another.
Code
1 2 3 4 5 6 7 |
function copyData() { const SS = SpreadsheetApp.getActiveSpreadsheet() const T_SHEET2 = SS.getSheetByName('Sheet2') const T_SHEET5 = SS.getSheetByName('Sheet5') T_SHEET2.getDataRange().copyTo(T_SHEET5.getRange(1, 1)) } |
Code Explanation
The code declares a function named copyData
. It uses the getActiveSpreadsheet
method to get the active spreadsheet. Then, it assigns the sheet objects T_SHEET2
and T_SHEET5
to the respective sheets with the names ‘Sheet2’ and ‘Sheet5’.
The getDataRange
method is used to get the entire data range from T_SHEET2
. The copyTo
method is then used to copy the data range to cell A1 in T_SHEET5
.
copyTo(T_SHEET5.getRange(1, 1)): This part does the work of copying the data range to the specified location.
- T_SHEET5: This part represents the Google Sheets sheet named ‘T_SHEET5’. The copied data will be pasted into this sheet.
- getRange(1, 1): This method gets the range representing the cells in the first row and first column of sheet ‘T_SHEET5’. The copied data will be pasted starting from this cell.
Example
Let’s say we have two sheets in our spreadsheet named ‘Source’ and ‘Destination’. We want to copy all the data from the ‘Source’ sheet to the ‘Destination’ sheet.
Here’s an example of how we can achieve this using the provided code:
1 2 3 4 5 6 7 |
function copyData() { const SS = SpreadsheetApp.getActiveSpreadsheet() const sourceSheet = SS.getSheetByName('Source') const destinationSheet = SS.getSheetByName('Destination') sourceSheet.getDataRange().copyTo(destinationSheet.getRange(1, 1)) } |
AI Prompt
Write a function that copies the data from one sheet to another in Apps Script. Use the copyTo
method to copy the data range from the source sheet to the specified range in the destination sheet.