使用按钮清除日期早于今天的行的内容

时间:2019-02-10 18:33:43

标签: google-apps-script google-sheets

我正在尝试使用一些Google Function来使其成为标题。我是个初学者,但我乐于接受挑战。我设法做了一个清除整个范围的按钮(C5:G102)。

但是我现在想要一个代码,仅清除早于今天的日期的范围。

我有主题,截止日期,描述等列。整个日期从C列到G列。因此,当我单击按钮时,我希望该行中所有截止日期都比今天更早的主题是清除了。日期在D列中。

能做到吗?

我只有这个:

function clearRange() {
  //replace 'Sheet1' with your actual sheet name
  var sheet = SpreadsheetApp.getActive().getSheetByName('ADD');
  sheet.getRange('C5:G102').clearContent();
}

所以,经过一番尝试,我想到了:但这不起作用...

function ClearOlder() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('ADD');
  var lastRow = sheet.getLastRow();
  var columnD = sheet.getRange(2, 4, sheet.getLastRow(), 1).getValues();
  var day = 24*3600*1000
  var today = parseInt((new Date().setHours(0,0,0,0))/day);

  for (var i=1; i < columnD.length; i++) {
    var dataday = parseInt(new Date(columnD[i][4]).getTime()/day);
    if (dataday < today) {sheet.getRange(i+1, 4, lastRow, 1).clearContent();}
  }
}

2 个答案:

答案 0 :(得分:0)

您实际上可以直接在javascript中比较日期。您不需要parseInt()函数。

var TEN_DAYS = 10 * 24 * 60 * 60 * 1000;
//             days hrs min   sec   ms

var expiry = new Date() - TEN_DAYS;

var date1 = new Date('2019-02-5');
var date2 = new Date('2019-02-1');
var date3 = new Date('2019-01-25');

console.log(expiry > date1); //Less than 10 days ago
console.log(expiry > date2); //Less than 10 days ago
console.log(expiry > date3); //More than 10 days ago

已更新:您的columnD选择器已关闭。

function clearOlder() { 
  //consider camelCase --> clearOlder() 
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 
  var lastRow = sheet.getLastRow(); 

  var columnD = sheet.getRange(2, 4, sheet.getLastRow(), 1).getValues(); //OP updated this to better fit their specific spreadsheet.

  var one_day = 24*3600*1000; 
  var expiry = new Date() - one_day; 

  for (var i=1; i < columnD.length; i++) { 

    var dataday = new Date(columnD[i][0]); 

    if (expiry > dataday) {
      sheet.getRange(i+1, 1, 1, 4).clearContent(); //OP updated this to better fit their specific spreadsheet.

    }
  } 
}

答案 1 :(得分:0)

是的!我知道了!

function clearOlder() { 
  //consider camelCase --> clearOlder() 
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); 
  var lastRow = sheet.getLastRow(); 

  var columnD = sheet.getRange(1, 4, sheet.getLastRow(), 5).getValues(); 

  var one_day = 24*3600*1000; 
  var expiry = new Date() - one_day; 

  for (var i=1; i < columnD.length; i++) { 

    var dataday = new Date(columnD[i][0]); 

    if (expiry > dataday) {
      sheet.getRange(i+1, 1, 1, 5).clearContent();

    }
  } 
}