Retrieve Values from Multiple 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 retrieve values from multiple sheets in Apps Script. We will write a function that retrieves values from two specific sheets in a Google Spreadsheet and logs them using the Logger service.
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
function getA1C3Values_4() { const SS = SpreadsheetApp.getActiveSpreadsheet(); const sheetNames = ['Sheet1', 'Sheet2']; const T_SHEET1 = SS.getSheetByName(sheetNames[0]); const value1 = T_SHEET1.getRange('A1:C3').getValues(); const T_SHEET2 = SS.getSheetByName(sheetNames[1]); const value2 = T_SHEET2.getRange('A1:C3').getValues(); Logger.log(value1); Logger.log(value2); } |
Code Explanation
The code defines a function named getA1C3Values_4
. It starts by getting the active spreadsheet using SpreadsheetApp.getActiveSpreadsheet()
. Two sheet names, ‘Sheet1’ and ‘Sheet2’, are defined in an array.
The code then retrieves the first sheet using SS.getSheetByName(sheetNames[0])
and gets the values in the range A1:C3 using T_SHEET1.getRange('A1:C3').getValues()
. The same process is repeated for the second sheet.
The values are logged using Logger.log
.
Example
When you execute the getA1C3Values_4
function, the values in the range A1:C3 from ‘Sheet1’ and ‘Sheet2’ will be logged in the Apps Script Logger.
AI Prompt
Write a function that retrieves values from two specific sheets in a Google Spreadsheet and logs them using the Logger service.
A function named getA1C3Values_4
should be created, and it should:
- Get the active spreadsheet
- Define an array of two sheet names
- Retrieve the values in the range A1:C3 from the first sheet
- Retrieve the values in the range A1:C3 from the second sheet
- Log the retrieved values using
Logger.log