I need help with Google Apps Script buttons in my spreadsheet. Right now I have two buttons that can add or subtract 1 from a single cell, but I want them to work across several columns at once.
My current script looks like this:
function increment() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var currentValue = sheet.getRange("C2").getValue();
var newValue = currentValue + 1;
sheet.getRange("C2").setValue(newValue);
}
function decrement() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var currentValue = sheet.getRange("C2").getValue();
var newValue = currentValue - 1;
sheet.getRange("C2").setValue(newValue);
}
I want to modify this so it works on columns D through J instead of just one cell. This is for tracking inventory numbers across different product categories. I’m pretty new to Google Sheets scripting so any simple explanation would be great.
yeah, just change it to getRange(“D2:J2”) and then loop through those cells. that really worked for me, super ez!
The range approach works, but you’ve got to handle the array values right. When you use getRange(“D2:J2”).getValues(), it returns a 2D array even for just one row. I hit this same issue building an inventory tracker last year. Here’s how to fix your functions:
function increment() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange("D2:J2");
var values = range.getValues()[0]; // Get first row as 1D array
for (var i = 0; i < values.length; i++) {
values[i] = values[i] + 1;
}
range.setValues([values]); // Wrap back in 2D array
}
The trick is grabbing the first row with [0] and wrapping the modified array back in brackets when setting values. This updates all columns in one shot instead of hitting each cell separately - way more efficient.
This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.