Fetching Values from A1:C3 for Multiple Sheets using for Iteration
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 fetch values from the range A1:C3 for multiple sheets in Apps Script. We will use a loop to iterate through a list of sheet names, access each sheet by name, and retrieve the values from the specified range.
Code
1 2 3 4 5 6 7 8 9 10 |
function getA1C3ValuesForIteration() { const SS = SpreadsheetApp.getActiveSpreadsheet() const sheetNames = ['Sheet1', 'Sheet2'] for (let i = 0; i < sheetNames.length; i++) { const sheet = SS.getSheetByName(sheetNames[i]) const value = sheet.getRange('A1:C3').getValues() Logger.log(value) } } |
Code Explanation
The code defines a function named getA1C3ValuesForIteration
. It first gets the active spreadsheet using SpreadsheetApp.getActiveSpreadsheet()
. The variable sheetNames
is an array that stores the names of the sheets we want to fetch values from.
A for
loop is used to iterate through each sheet name. Inside the loop, the getSheetByName()
method is used to retrieve the sheet object based on the name. Then, the getRange()
method is used to specify the range A1:C3, and the getValues()
method is used to retrieve the values within that range as a 2D array.
The retrieved values are logged using Logger.log()
.
Example
When you run the getA1C3ValuesForIteration
function, it will fetch the values from the range A1:C3 for each sheet specified in the sheetNames
array. The retrieved values will be logged in the Apps Script Logger.
AI Prompt
Write a function that fetches values from the range A1:C3 for multiple sheets in Apps Script. Use a loop to iterate through an array of sheet names, access each sheet by name, and retrieve the values from the specified range. Log the retrieved values.