简体   繁体   中英

Copy cells to another sheet when values increase

Yesterday I asked this question: Send email notification when values in different columns increase Basically, I have an array of percentage calculations, and if the values in different columns on the last row change and meet the increase criteria, they should be copied on another sheet.

I tried to change the code accordingly:

function compareValue() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Perc");
  var data = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
  var list = []; 

  for(var i=0; i<data[0].length; i++){

    var title = data[0][i]; 
    var value = parseFloat(data[data.length -1][i]); /

    if(value >= 2){     
      var element = [title, value];    
      list.push(element)                
    }    
  }

  if(list.length >= 1){ 
    setValues(list);
  }
}


function setValues(list) {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Alert");
  sheet.getRange('A1:Z50').clearContent();
  var title = sheet.getRange(1, 1, list.length);
  var value = sheet.getRange(1, 2, list.length);

  for(var i=0; i<list.length;i++){
    title.setValue(list[i][0]);
    value.setValue(list[i][1]);
  }

}

Now the problem is when I have only one cell that changed everything is fine, but when there are multiple cells the script only copy one value, and it is repeated for the number of values that should be. For example, if 4 cells increase over the value 2, then only one value is copied and it is repeated 4 times. What am I doing wrong? thank you

The problem is on your value set. On your code, you set the value for the all range with the last value on the list, cause it's the last value on your for loop. Consider using range.setValues() which is simple to use.

function compareValue() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Perc");
  var data = sheet.getRange(1, 1, sheet.getLastRow(), sheet.getLastColumn()).getValues();
  var list = []; 

  for(var i=0; i<data[0].length; i++){

    var title = data[0][i]; 
    var value = parseFloat(data[data.length -1][i]);

    if(value >= 2){     
      var element = [title, value];    
      list.push(element)                
    }    
  }

  if(list.length >= 1){ 
    setValues(list);
  }
}


function setValues(list) {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Alert");
  sheet.getRange('A1:Z50').clearContent();
  var range = sheet.getRange(1, 1, list.length, list[0].length);

  range.setValues(list);

}

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