【问题标题】:Setting background color based on date plus根据日期加设置背景颜色
【发布时间】:2019-09-26 19:22:54
【问题描述】:

我需要根据 B 列中的日期创建一个脚本,根据 b 列中的日期是一天、两天、三天等,将行的背景颜色从 B 列更改为 d 列. 在今天之前。

我从另一篇文章中找到了一些代码,但是它正在评估带有日期的多行

function formatting() {
  var sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Schedule Fields');
  var rg=sheet.getDataRange();//this range starts at column 1
  var vA=rg.getValues();
  var today = new Date();
  for(var i=0;i<vA.length; i++){
    for(var j=1;j<=1;j++){//j=2 is the third column
      var bullDate = new Date(vA[i][j]);  
      if (bullDate < today){
        sheet.getRange(i+1,j+1).setBackgroundColor('yellow');
      }
    }
  }
}

我能够更改此代码足以获得 B 列中日期的背景颜色。我不确定如何更改此代码以设置 ColB-ColD 的背景颜色,然后添加到 if 条件以等同于1 天 2 天 3 天 等在今天的未来。

function formatting() {
  var sheet=SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses');
  var rg=sheet.getDataRange();//this range starts at column 1
  var vA=rg.getValues();
  var today = new Date();
  for(var i=0;i<vA.length; i++){
    for(var j=2;j<=4;j++){//j=2 is the third column
      var bullDate = new Date(vA[i][j]);  
      if (bullDate < today){
        sheet.getRange(i+1,j+1).setBackgroundColor('yellow');
      }
    }
  }
}

这是我从conditionally formatting cells based on date使用的完整原始sn-p

【问题讨论】:

  • 请分享你用过的完整sn-p (HTML/JS)
  • 我在帖子中添加了完整的 sn-p。
  • 您能否分享一个经过清理的工作表版本,以便更好地查看数据的排序方式?至于更改颜色,最好使用setBackgroundColors() 一次进行批量更改,但是一旦我看到表格,就会更容易向您展示如何。

标签: javascript google-apps-script


【解决方案1】:

试试这个:

function colors(){
  var ss = SpreadsheetApp.getActive().getSheetByName("allGroups");
  var data = ss.getDataRange().getValues();
  var colors = ss.getDataRange().getBackgrounds();
  var today = new Date();
  var date = new Date(data[2][1])
  var diffTime, diffDays

  for (var i = 0; i < data.length; i++){
    date = new Date(data[i][1]); // Current date to evaluate in the sheet.
 // diffTime = today - date;
    diffTime = date - today;  
    diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    if (diffDays == 1){
      colors[i][1] = "red";
      colors[i][2] = "red";
      colors[i][3] = "red";
    }
    else if (diffDays == 2){
      colors[i][1] = "yellow";
      colors[i][2] = "yellow";
      colors[i][3] = "yellow";
    }
  }
  ss.getDataRange().setBackgrounds(colors);
}

此代码会将B 列中的日期与今天进行比较,如果相隔 2 天,则将日期单元格设置为黄色,如果相隔一天,则将其设置为红色。

【讨论】:

  • 我希望 C 列和 D 列中的单元格也改变背景。
猜你喜欢
  • 1970-01-01
  • 2021-07-09
  • 2015-04-21
  • 2016-07-09
  • 1970-01-01
  • 2013-04-30
  • 2011-12-27
  • 1970-01-01
  • 2015-07-17
相关资源
最近更新 更多