首页 文章

Google Script:getValue来自今天的日期

提问于
浏览
0

我正在使用谷歌工作表脚本,我正在尝试识别超过特定阈值的值 . 在这种情况下,有3个变量f1,f2和pf . 当具有最高值(三个中的一个)的单元格超过500时,它将该值写入另一个单元格 . 最终游戏是创建一个onEdit触发器,它将能够自动检查每天输入的值,并在违反限制时发送电子邮件通知 . 但为了简单起见,我现在已经错过了这一点 . 我正在努力让脚本从包含今天日期的行获取getValues() .

这是一个数据示例

A          B       C        D
    ____________________________________
1   |                  H2S values
2   | Date       f1      f2      pf
3   |30/10/17   971.4   1037.6   809
4   |31/10/17   795.6   795.1    576
5   |01/11/17    429    444.3   351.8

它取代了今天日期的行,而是占据了日期范围的顶行 . 其余的代码在限制和最高值方面工作,但我无法弄清楚如何将行与日期匹配 . 'today_row'应该返回与日期匹配的行号,即01/11/17'Today_row'应该等于5,但它返回'daterange'中的第一行,因此返回第3行 .

这是我正在处理的代码:

function readCell() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet();

  // set today's date
  var date = sheet.getRange("F1").setValue(new Date());
  // look up date range
  var daterange = sheet.getRange("A3:A");
  // find the row position of today's date
   if (date = daterange) {
   var today_row = daterange.getRow();
   var today_set = sheet.getRange("F2").setValue(today_row); }

  // set today's variables and show value in cell
    var today_h2s_f1 = sheet.getRange("B"+today_row).getValue();
    var today_f1_set = sheet.getRange("F3").setValue(today_h2s_f1);
    var today_h2s_f2 = sheet.getRange("C"+today_row).getValue();
    var today_f2_set = sheet.getRange("F4").setValue(today_h2s_f2);
    var today_h2s_pf = sheet.getRange("D"+today_row).getValue();
    var today_pf_set = sheet.getRange("F5").setValue(today_h2s_pf);

  // Set value of cell if the h2s level exceeds 500ppm, highest value out of f1,f2 and pf is chosen
    if (today_h2s_f1 > 500 && today_h2s_f1 > today_h2s_f2 && today_h2s_f1>today_h2s_pf) {
      var highest_h2s = sheet.getRange("F6").setValue(today_h2s_f1)}
    else if (today_h2s_f2 > 500 && today_h2s_f2 > today_h2s_f1 && today_h2s_f2 >today_h2s_pf){
      var highest_h2s = sheet.getRange("F6").setValue(today_h2s_f2)}
    else if (today_h2s_pf > 500 && today_h2s_pf > today_h2s_f1 && today_h2s_pf >today_h2s_f2){
      var highest_h2s = sheet.getRange("F6").setValue(today_h2s_pf)}
  }

任何帮助将不胜感激 - 谢谢 .

1 回答

  • 0

    获取 daterange 会为您提供一个范围对象,您需要迭代以匹配特定的单元格 . 首先,我们需要获取一系列日期,然后在比较之前使时间戳信息无效 . 进行以下更改:

    // set and store a date object for today
    var date = sheet.getRange("F1").setValue(new Date()).getValue();
    
    // Get the range of dates to test
    var daterange = sheet.getRange("A3:A").getValues()
    
    // iterate the values in the range object
    for(var i=0; i<daterange.length; i++) {
    
      // Compare only month/day/year in the date objects
      if(new Date(daterange[i]).setHours(0,0,0,0) == date.setHours(0,0,0,0)) {
    
        // if there's a match, set the row
        // i is 0 indexed, so add 3 to get the correct row
        var today_row = (i+3);
    
        // rest of your code
      }
    }
    

    我没有测试 if 块中设置的每个变量,但是这个位返回正确的日期评估以及正确的行 .

相关问题