如果小于当前日期,则删除范围内的单元格

时间:2017-02-27 02:36:04

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

我有一系列明文格式的日期(必须保持这种方式),如果每个范围单元格中的日期小于当前日期,我需要在凌晨1点清除它们。我可以稍后设置运行计划,但任何人都可以告诉我为什么这不起作用吗?

我使用= TEXT(TODAY()," m / dd")在单元格AE3中以正确的格式插入当前日期。

谢谢!

function clearOldDate() 
{

    var ss = SpreadsheetApp.getActiveSpreadsheet();  
    var sheet = ss.getSheetByName("Loads");
    var cells = sheet.getRange('AC9:AE33').getValues();
    var data = [cells];

    var date = sheet.getRange('AE3').getValues();
    //var Sdate = Utilities.formatDate(date,'GMT+0900','MM/dd');



    for(i=0; i<76; i++) 
    {


          if (date > data[i])
          {
              data[i].clear();  
          };
    };
 };

1 个答案:

答案 0 :(得分:0)

这应该可以解决问题

function clearOldDate() 
{

    var ss = SpreadsheetApp.getActiveSpreadsheet();  
    var sheet = ss.getSheetByName("LogSheet");
    //getValues gives a 2D array. 
    var data = sheet.getRange('AC9:AE33').getValues();

    var date = sheet.getRange('AE3').getValues();
    //var Sdate = Utilities.formatDate(date,'GMT+0900','MM/dd');


    //This for loop with loop through each row
    for(i=0; i<data.length; i++) 
    {
          //This for loop with loop through each column
         for (var j = 0; j < data[i].length ; j ++){
          //This assumes Column AC has the dates you are comparing aganist
          if (date > data[i][j])
           {   
              //sets that the Row with index i to empty
              data[i] =  ["","",""]
           };
          }
    };
     //finally set the value back into sheet
     sheet.getRange('AC9:AE33').setValues(data)
     };

基本上,一旦修改了数据数组,就需要setValues。

注意:当将值存储为文本时,此语句(日期&gt; data [i] [0])无法按预期工作。

编辑:根据评论修改代码并添加新的for循环以浏览每一列