【问题标题】:Google Script to check sheet column values用于检查工作表列值的 Google 脚本
【发布时间】:2020-06-02 17:38:52
【问题描述】:

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

我想做的是创建一个每小时运行的谷歌脚本(通过可安装的触发器)并在 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 列,并将另一个函数(如下所示)的结果返回到 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
    }

【问题讨论】:

    标签: google-sheets


    【解决方案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);
        }
      }
    }
    

    【讨论】:

    • 请注意,getValues() 返回一个数组数组,在这种情况下,它将返回类似 [ [Y], [N], [Y], [N] ] 的内容。因此,如果您访问array[valuesIdx],它将返回[Y] 而不是Y,您将无法将其与字符串进行比较。为了解决这个问题,您可以简单地将主数组getValues().flat() 转换为[ Y , N , Y , N] 并使array[valuesIdx] 返回Y
    • 哦,有趣的是,我在测试中没有发现这一点,因为在 Javascript "Y" == ["Y"] 中。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多