Google Apps Script add 1 to the value of a cell in

2019-07-31 14:33发布

问题:

I am trying to set up a sign up app where it counts the number of yes, maybe and no responses. Can someone show me how to add 1 to the value of a cell within a spreadsheet from an app? Below is the function that I am using for the Yes button on my app, I have added the click handler to the app.

function yesButton(e){
  var app = UiApp.getActiveApplication();
  var ss = SpreadsheetApp.openById('spreadsheet ID').getSheets()[0];
  var yesCount = ss.getRange("A2");
  var yesAdd = yesCount.getValues();
  var yesTotal = (yesAdd.value) + 1;
  yesTotal.setValue(yesAdd);

  return app;
}

回答1:

When you call getValues(), you obtain a 2D array. Which is referenced like this. yesAdd[row#][col#]. Instead, you should use the function getValue() which returns just a single value (not in an array).

Just change the one line to

var yesAdd = yesCount.getValue();

Then write back to the cell that you read it from.

yesCount.setValue(yesAdd+1);

yesCount still refers to the cell that you'd like to edit, so we set the value on that cell.



回答2:

Just used this and it worked perfectly, wanted a simple plus minus script to use with some invisible buttons and it works.

I just split mine into plus and minus for current sheet..

function plus() {

var ss = SpreadsheetApp.getActiveSpreadsheet();

var yesCount = ss.getRange("B7");

var yesAdd = yesCount.getValue();

yesCount.setValue(yesAdd+1);

}

.

function minus() {

var ss = SpreadsheetApp.getActiveSpreadsheet();

var yesCount = ss.getRange("B7");

var yesAdd = yesCount.getValue();

yesCount.setValue(yesAdd-1);

}