Google脚本检查工作表列值

时间:2020-06-02 17:38:52

标签: google-sheets

我有一个Google表格,其中B列的每个单元格中都有一个公式,该公式根据特定条件使用IF公式返回“ Y”或“ N”。

我想做的是创建一个每小时运行一次(通过可安装的触发器)的google脚本,并在B列中搜索单元格中所有带有“ Y”的行。然后,我希望它接受这些行并从C列中提取值,然后使用这些值通过该行中C中的值来推送另一个函数,并在该行的D列中返回结果,然后对每行重复一次在B列中找到了“ Y”。基于在Stack中的搜索,我找到了将搜索该列的代码。但是我无法弄清楚如何使用数据从相邻列C提取值以推送我的其他函数,然后将结果返回到列D。同样,在此代码上运行简单测试时,它看起来像唯一的运行第2行,而不在工作表中搜索其他任何行。

    function onSearch()
{
    var searchString = "Y";
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of DataFinal"); 
    var column =2; //column Index   
    var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues(); //1st is header row
    var searchResult = columnValues.findIndex(searchString); //Row Index - 2

    if(searchResult != -1)
    {
        //searchResult + 2 is row index.
        SpreadsheetApp.getActiveSpreadsheet().setActiveRange(sheet.getRange(searchResult + 2, 3)).setValue("found here");
    }

这是我想包含在搜索脚本下的代码,然后将找到的行(带有“ Y”)中的值推送通过,并将另一个函数(如下所示)的结果返回到D列。

    var timedis = gettime(value) \\ this is where i would take the value from column C push it through my other function 
      o.setValue(timedis). \\ the result of gettime (timedis) is what i woudld like to put in column D in the same row and then repeat for all rows where "Y" was found in B. 
}

    function gettime(f) {
      \\my other function script would go here. No help needed on this part. 

    return timedis
    }

1 个答案:

答案 0 :(得分:1)

您可以使用常规的for循环遍历整列并执行所需的操作:

function onSearch() {
  var searchString = "Y";
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of DataFinal"); 
  var column = 2; //column Index   
  // start getRange at 2 to skip header row
  var columnValues = sheet.getRange(2, column, sheet.getLastRow()).getValues().flat(); 

  for (let valuesIdx = 0; valuesIdx < columnValues.length; valuesIdx++) {
    if (columnValues[valuesIdx] === searchString) {
      // row number is valuesIdx + 2 because of skipping header row 
      // and because rows in getRange are 1-indexed
      nextColVal = sheet.getRange(valuesIdx + 2, column + 1).getValue();
      let timedis = gettime(nextColVal);
      sheet.getRange(valuesIdx + 2, column + 2).setValue(timedis);
    }
  }
}
相关问题