Inserting a Value in Google Sheets using 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 insert a value into a cell in Google Sheets using Apps Script. We will learn how to use the setValue()
method to set the value of a cell in a specific sheet.
Code
1 2 3 4 5 6 |
function insertValue() { const SS = SpreadsheetApp.getActiveSpreadsheet() const sheet = SS.getSheetByName('Sheet1') let cell = sheet.getRange('A1') cell.setValue(1) } |
Code Explanation
The code defines a function called insertValue()
. Inside the function, we first get the active spreadsheet using getActiveSpreadsheet()
method and assign it to the SS
variable.
We then use the getSheetByName()
method to retrieve the sheet named ‘Sheet1’ and assign it to the sheet
variable.
Next, we use the getRange()
method to get the range of cell ‘A1’ in the sheet and assign it to the cell
variable.
Finally, we use the setValue()
method to set the value of the cell to 1.
Example
Let’s say we have a Google Sheet named ‘Data’ and we want to insert the value 42 into cell ‘B5’. We can use the following code:
1 2 3 4 5 6 |
function insertValue() { const SS = SpreadsheetApp.getActiveSpreadsheet() const sheet = SS.getSheetByName('Data') let cell = sheet.getRange('B5') cell.setValue(42) } |
AI Prompt
Write a function that inserts the value 5 into cell ‘C10’ in a Google Sheet named ‘Sheet1’ using Apps Script.