Search code examples
google-apps-scriptgoogle-sheetssimplify

How can I simplify my google app script I copy/pasted multiple times for each of my different ranges?


I already searched stackoverflow for a solution, but to no success. It seems I don't know how to "name" my problem correctly ...

I found two functions for my Google sheet that help me count successes and losses at work. They work wonderfully.

plus1() adds +1 to a value in A1

function plus1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var yesCount = ss.getRange("A1");
var yesAdd = yesCount.getValue();
yesCount.setValue(yesAdd+1);
}

minus1() subtracts 1 to a value in A1:

function minus1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var yesCount = ss.getRange("A1");
var yesAdd = yesCount.getValue();
yesCount.setValue(yesAdd-1);
}

I edited my question for clarification I increment or decrement the cells individually, not all at once. For example: This morning I incremented 1 to cell A1. This afternoon I decremented 3 to cell A1. Also, I attached those scripts to a custom menu bar with ui.createMenu.

My problem: I use 6x the same script only with different ranges:

1) plus1A() with Range A1
2) plus1B() with Range A2
3) plus1C() with Range A3
4) minus1A() with Range A1
5) minus1B() with Range A2
6) minus1C() with Range A3

My questions: Isn't there a way to simplify the script so I don't end up with 6 times the same code, that only differ in ranges?

Many thanks for your valuable time! Ron


Solution

  • If you don't mind to have four or six or any number of separate functions and all you need is to make them simpler, here is the possible way:

    # six functions for custom menu
    
    function a1_plus()  { change('a1',  1) }
    function a1_minus() { change('a1', -1) }
    
    function a2_plus()  { change('a2',  1) }
    function a2_minus() { change('a2', -1) }
    
    function a3_plus()  { change('a3',  1) }
    function a3_minus() { change('a3', -1) }
    
    
    # inner function
    
    function change(range, value) {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var r  = ss.getRange(range);
      var v  = r.getValue();
      r.setValue(v + value);
    }