简体   繁体   中英

Add value of a cell to another cell for all cells in a column in Google Appscript

I want to assign a script to the + button, such that when I press the button, cell M4 will be added with the value from cell R4, M5 with value from R5, and so on until the end of the column.

Screenshot

This is my script

function add() {
s=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var rangeVal=s.getRange("M:M")
var rangeVal2=s.getRange("R:R")
var Val=rangeVal.getValues()
var Val2=rangeVal2.getValues()
for (var i=4; i<Val.length; i++) {
if (Val2[i][0] > 0 ) {
  Val[i][0] = Val[i][0] + Val2[i][0]; } } 
rangeVal.setValues(Val);
}
function add() {
  s=SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
  var rangeVal=s.getRange("M:M")
  var rangeVal2=s.getRange("R:R")
  var Val=rangeVal.getValue() // <= you went wrong here
  var Val2=rangeVal2.getValue() // <= & here
  for (var i=4; i<Val.length; i++) {
    if (Val2[i][0] > 0 ) {
      Val[i][0] = Val + Val2; // <= & here
    } 
  } 
  rangeVal.setValue(Val); // <= & here
}

Just a few typos are stopping this working (some that i missed in my initial inspection!), otherwise the logic is correct. You're calling range.getValue() , which returns the top left value of the range as a string, but you want to use range.getValues() (with an 's' at the end of the function name) to retrieve all of the values in the range as a 2D array. You also need to use range.setValues() at the end to write the values back to the spreadsheet. Finally, you've very carefully stepped through the data arrays, but each time you loop you're concatenating Val & Val2 . You need to add the specific values together: Val[i][0] += Val2[i][0] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM