2013-04-14 86 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

相關問題