Google脚本:如果单元格包含的日期比今天的日期早10天,如何隐藏行

时间:2020-09-25 17:55:04

标签: javascript google-apps-script google-sheets

我有一个电子表格,其中B列中的单元格包含自动设置的日期。 如果今天和这些日期之间的差大于10天,我想隐藏相应的行。

我已尝试按以下方式对其进行编码,但是我被卡住了,需要帮助,请:

 function onEdit(e) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
    var s = ss.getSheetByName("Sheet1");   // The name of the sheet    
    var row = s.getRange('B:B').getValues(); // it's the column that contains cells with dates 
    var today = new Date(); // today's date
    
    s.showRows(1, s.getMaxRows());
    for(var i=0; i< row.length; i++){ if(today - row[i]>10 ) { s.hideRows(i+1, 1); } 
         
    }}

关于如何修复代码的任何建议?

1 个答案:

答案 0 :(得分:2)

常规功能:

如果要对 B列中的所有单元格进行迭代操作,则可以使用常规函数并从脚本编辑器:

function myFunction(){

  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName("Sheet1");
  const today = new Date();
  
  const check_values = sh.getRange('A1:A'+sh.getLastRow()).getValues().flat();
  const date_values = sh.getRange('B1:B'+sh.getLastRow()).getValues().flat();
  
  date_values.forEach((d,index)=>{
                      
     var diffTime = Math.abs(today - d);  
     const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
     if (diffDays > 10 && check_values[index]=='Yes'){
        sh.hideRows(index+1);
     }
  })
  }

onEdit(e)函数

如果要使用onEdit(e)函数,即在 B列中的单元格进行编辑时,检查是否需要隐藏行,然后使用:

function onEdit(e){

  const row = e.range.getRow();
  const col = e.range.getColumn();
  const as = e.source.getActiveSheet();
  
  const today = new Date();
  const date2 = new Date(e.range.getValue());
  const diffTime = Math.abs(today - date2);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
  
  if ( as.getName() == "Sheet1" && col == 2 && diffDays > 10){ 
  as.hideRows(row);
  }
}

在两种情况下,请确保 Sheet1 B列中的日期实际上是日期对象,而不是文本。要进行检查,请使用公式=isdate(B1),如果返回的是 true ,则表示B1是日期对象。


参考: