I successfully created increment and decrement buttons in my Google Sheets using Apps Script, but they only work for a single cell. I need these buttons to work across several columns for inventory management.
Here’s my current working code:
function increment() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var currentValue = sheet.getRange("C1").getValue();
var newValue = currentValue + 1;
sheet.getRange("C1").setValue(newValue);
}
function decrement() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var currentValue = sheet.getRange("C1").getValue();
var newValue = currentValue - 1;
sheet.getRange("C1").setValue(newValue);
}
How can I modify this to work with a range of columns, for example from column D through J? I’m new to Google Apps Script and would appreciate any guidance on extending this functionality to multiple columns.
Here’s a better approach - detect which column the user clicked on dynamically. Use getActiveRange() to grab the current selection, then apply the increment/decrement to that specific column.
function smartIncrement() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var activeRange = sheet.getActiveRange();
var column = activeRange.getColumn();
if (column >= 4 && column <= 10) { // Columns D through J
var currentValue = sheet.getRange(1, column).getValue();
var newValue = currentValue + 1;
sheet.getRange(1, column).setValue(newValue);
}
}
You’ll only need two functions instead of creating separate ones for each column. Just select the column you want to modify before clicking the button. I’ve used this method for about six months now - way more maintainable when you’re dealing with lots of columns.
Here’s what worked best for me with multiple columns - pass the column info as a parameter to your functions. Just add a column parameter to your existing code and create separate button functions for each column.
Like this:
function adjustValue(column, increment) {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var currentValue = sheet.getRange(column + "1").getValue();
var newValue = currentValue + increment;
sheet.getRange(column + "1").setValue(newValue);
}
Then make specific functions for each column:
function incrementD() { adjustValue("D", 1); }
function decrementD() { adjustValue("D", -1); }
function incrementE() { adjustValue("E", 1); }
function decrementE() { adjustValue("E", -1); }
I used this for my inventory system with 8 different product categories and it worked great. Each button clearly matches its column, so it’s super easy to assign them to specific cells or drawings in your sheet.
u can loop through all columns at once instead of hitting them one by one. just use a for loop on cols D through J - way faster for bulk updates when u’re adjusting multiple inventory items.