Search code examples
arraysgoogle-apps-scriptincrementdistinct-valuesdecrement

Increment (and Decrement) values in a [Google Sheet] column


enter image description here

The image (attached) is a simple "AppScript" adapted from a popular YouTube ...that allows "Values" (in a column) to be increased by 1 - by clicking an "Arrow" (button) - that I've linked to the script

enter image description here

By Clicking the "Up" Arrow, all the values will change from 6 ...to 7 (ie: go "Up" by one value)

enter image description here

QUESTION(s): How do I 'adjust' the Script to:

  1. Assess (or Evaluate) the Values in the column
  2. Ignore any values that are "Zero" (0)
  3. Increment (by 1) ...all the other "Non-Zero" values

And finally, if a Value is 'different' than the other values (eg: 5 ...instead of 7)

  1. Increment a value of 5 to 6 ...and the 'other' values of 7 to 8

enter image description here

Currently, the Script will change 5 to an 8 (along with all the 7's)

enter image description here

I'd like the Script to change the 5 to a 6 (and the 7's can increment to 8's)


Solution

  • Suggestion:

    You can have the script iterate through each of the value of the range and increment it if the value isn't equal to 0.

    Do try this script:

    function incrementA2A5() {
      var sourceSheet = SpreadsheetApp.getActiveSheet();
      var range = sourceSheet.getRange("A2:A5");
      var values = range.getValues();
    
      //The forEach loop below iterates through each value of the range.
      //If the value isn't equal to zero, the loop will increment it by one.
    
      values.forEach(x => x[0] != 0 ? x[0] += 1 : x[0]);
    
      range.setValues(values); //Sets the updated values on the range
    }
    

    .GIF demo of the script: enter image description here