Copying Data with Conditions 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 from one sheet to another with specific conditions using Apps Script. We will learn how to use the copyTo
method to copy data and apply various options such as copying only values or including formatting.
Code
1 2 3 4 5 6 7 8 9 |
function copyDataWithConditions() { const SS = SpreadsheetApp.getActiveSpreadsheet() const T_SHEET2 = SS.getSheetByName('Sheet2') const T_SHEET4 = SS.getSheetByName('Sheet4') T_SHEET2.getDataRange().copyTo(T_SHEET4.getRange('A1'), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false) T_SHEET2.getDataRange().copyTo(T_SHEET4.getRange('A1'), SpreadsheetApp.CopyPasteType.PASTE_COLUMN_WIDTHS, false) } |
Code Explanation
The code defines a function named copyDataWithConditions
. It retrieves the active spreadsheet and assigns it to the SS
variable. It then gets references to two sheets, T_SHEET2
and T_SHEET4
, using their names.
The getDataRange()
method is used to retrieve the range of data in T_SHEET2
. The copyTo()
method is then called on this range, specifying the target range A1
in T_SHEET4
to copy the data to. The SpreadsheetApp.CopyPasteType.PASTE_NORMAL
option is used to copy only values without formatting.
Similarly, another copyTo()
method is called to copy the column widths from T_SHEET2
to T_SHEET4
using the SpreadsheetApp.CopyPasteType.PASTE_COLUMN_WIDTHS
option.
Example
Consider a scenario where you have a spreadsheet with two sheets named “Data” and “Summary”. You want to copy the data from the “Data” sheet to the “Summary” sheet preserving column widths. You can use the copyDataWithConditions
function to achieve this:
1 2 3 4 5 6 7 8 9 |
function copyDataWithConditions() { const SS = SpreadsheetApp.getActiveSpreadsheet() const dataSheet = SS.getSheetByName('Data') const summarySheet = SS.getSheetByName('Summary') dataSheet.getDataRange().copyTo(summarySheet.getRange('A1'), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false) dataSheet.getDataRange().copyTo(summarySheet.getRange('A1'), SpreadsheetApp.CopyPasteType.PASTE_COLUMN_WIDTHS, false) } |
AI Prompt
Write a function that copies data from one sheet to another with specific conditions. Use the copyTo
method to copy the data and apply options such as preserving column widths. Make sure to retrieve the active spreadsheet and specify the sheet names dynamically.