2013-04-14 87 views
0

我正在研究由多人编辑的Google电子表格。它用于跟踪各种成员统计信息,因此它们每个只更新一行。我试图做的是检查行中的单元格何时更新,并根据更新的日期更改该行中另一个单元格的背景。检查单元格更新Google电子表格

function onEdit() { 
var s = SpreadsheetApp.getActiveSheet(); 
if(s.getName() == "HT ~ Stats") { //checks that we're on the correct sheet 
    var r = s.getActiveCell(); 
    if(r.getColumn() == 7) { //checks for the correct column 
    var dateCell = r.offset(0,21); 
    //var date = new Date() 
    var date = Utilities.formatDate(new Date(), "GMT", "MM-dd-yyyy") 

    dateCell.setValue(date); //sets column AB of selected row to the date of the update 

}; 
} 

在这一点上,我陷入了困境。这一点之后我想要发生的事情是将var日期的值与当前日期进行比较。一旦得到比较,如果结果在当前日期的3天之内,我希望所选行中的第一个单元格将其背景更改为绿色。

这是我平生第一次做任何事情在谷歌的脚本,所以我敢肯定有任何更容易或更好的方法来做到这一点。感谢您的帮助:)

回答

0

我没有测试以下,但它的东西,可能让你在正确的轨道上。它基本上完成了上面的操作,但是在第二次编辑时,它获取原始日期,将其转换为整数,获取新的日期整数,计算差异,如果大于3天(以毫秒为单位),则设置第一个单元格的背景颜色。

它可能需要一些调整,但我希望它能帮助。

function onEdit() { 
    //G ets current spreadsheet 
    var s = SpreadsheetApp.getActiveSheet(); 
    // If on the right spreadsheet 
    if(s.getName() == "HT ~ Stats") { 
    // Gets the active cell 
    var r = s.getActiveCell(); 
    // If on the right column 
    if(r.getColumn() == 7) { 
     // Sets the AB column 
     var dateCell = r.offset(0,21); 
     // Retrieves the currentDate 
     var currentDate = dateCell.getValue().getTime(); 
     // Creates a new date 
     var date = new Date(); 
     // Adds the date to the AB cell 
     dateCell.setValue(date); 
     // Creates a date integer 
     var dateInt = date.getTime(); 
     // Works out the difference of the current date and new date 
     var difference = dateInt - currentDate; 
     // Creates a 3 day integer 
     var threeDays = 259200000; 
     // If the difference is greater than 3 days. 
     if(difference >= threeDays) 
     { 
     //Set the first cell background colour. 
     r.offset(0,-6).setBackgroundColor("#D3E375"); 
     } 
    } 
    } 
} 
+0

它的工作原理。万分感谢。我初始时遇到了问题,但后来我意识到它必须先在AB单元中有一个日期。由于并非所有的单元格都已经存在,所以它没有正确更新。 现在我想使它自动检查并相应更新,而不是依赖更新的单元格。我正在制定一个'聚光灯'系统。 3或更新后的几天为绿色,更新后4至6天为黄色,之后的任何内容都会变为红色。 因为它会一直是绿色的,因为它只会在更改时更新。 – Buzz1316

+0

很高兴帮助。如果你想要不断地检查更新值的东西,我会建议创建一个单独的函数,在日期列中的所有单元格中迭代新的日期对象。成功完成手动运行后,您可以设置['triggers'](https://developers.google.com/apps-script/understanding_triggers#TimeTriggers),以特定的时间间隔运行某个功能。 ....如果一个答案已经帮助,不要忘记接受它与滴答:) – dev

+0

可以用onOpen函数设置它吗?如果是的话,最好的办法是什么?为新的Date()设置var,然后将每个AB列与它进行比较?我需要为每个AB列设置一个新的变量,还是有办法从指定的单元格中绘制数据?对不起,如果这些事情很简单,但我从来没有真正做过这样的事情。 – Buzz1316

相关问题