[英]Google script: How to hide a row if a cell contains a date 10 days older than today's date
我有一個電子表格,其中 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); }
}}
關於如何修復代碼的任何建議?
常規功能:
如果要對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 是日期對象。
參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.