如何检查列中是否有新值?

时间:2017-12-24 23:02:30

标签: google-apps-script google-sheets

我想从每天刷新的API检查排名前30位的新名称,然后将每个新名称附加到其他列,如果它不在那里。

我认为for循环将是解决方案。这是我到目前为止所得到的。

function appendValues(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var top30Names = ss.getRange("A4:A33").getValues();
  var eligibleNames = ss.getRange("P4:P300").getValues();
  for (i = 0; i < 30; i++){
    var searchKey = top30Names[i]; // search if the eligible name is in the top30names
    if (isInArray(searchKey, eligibleNames)){
      // do nothing
    }
    else{
      getFirstEmptyRow();
      ss.getActiveCell().setValue(searchKey);
    }
  }
}

function isInArray(value, array) {
  return array.indexOf(value) > -1;
}

function getFirstEmptyRow() {
    var sheet = SpreadsheetApp.getActiveSheet(),
        values = sheet.getRange("P4:P300") // the range to search for the first blank cell
            .getValues(),
        row = 0; //start with the first array element in the 2D array retrieved by getValues()
    for (row; row < values.length; row++) {
        if (!values[row].join("")) break;
    }
    return sheet.setActiveSelection("P" + (row + 4)).getRow();//.getLastRow() // column between "" and row + starting_row in range

}

每次追加前30名,但我只需要新值。

1 个答案:

答案 0 :(得分:0)

我找到了使用setFormula的工作。如果有人有更优雅的解决方案,我会很开心。

function appendNewName(){
  setFormula();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var newNames = ss.getRangeByName("newEntries").getValues(); 
  for (i = 0; i < 30; i++){
    getFirstEmptyRow();
    var x = newNames[i][0];
    // Logger.log(x); // What does this do???
    if (x.length > 1) {
      ss.getActiveCell().setValue(newNames[i]);
    }
  }
}
function setFormula(){
  // first run this
  clearFormula();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.getRangeByName("newEntries").setFormula("=IF(ISNUMBER(MATCH(A4,AppendNew,0)),\"\",A4)"); // Sets a formula to the range that will show the new daily entries in top 30
}

function clearFormula(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.getRangeByName("newEntries").clear(); 
}

function getFirstEmptyRow() {
    var sheet = SpreadsheetApp.getActiveSheet(),
        values = sheet.getRange("appendNew") // the range to search for the first blank cell
            .getValues(),
        row = 0; //start with the first array element in the 2D array retrieved by getValues()
    for (row; row < values.length; row++) {
        if (!values[row].join("")) break;
    }
    return sheet.setActiveSelection("P" + (row + 4)).getRow(); // column between "" and row + starting_row in range
}