你有幾分接近,但取決於你想要做什麼,這可能最終會被相當複雜。儘管如此,你正走在正確的軌道上。
你想要做的第一件事就是在你的電子表格中獲取值作爲活動範圍。
var myDataVals = SpreadsheetApp.getActiveSheet().getActiveRange().getValues();
這將一個2維數組指派給myDataVals
。
從這裏開始,您可以循環訪問外部數組(逐行),然後循環訪問每個內部數組(逐列)。有很多方法可以解決這個問題,它確實取決於你想要做什麼。您可以在此處瞭解有關基本JavaScript編程的更多信息:https://www.javascript.com/resources
我寫了一個示例函數,您可以使用它。我的解決方案是遍歷行(外部數組),然後將它們分配給一個對象,其中鍵是員工姓名;這有效地按名稱排序行。然後我按照時間戳值降序排列每個名稱中的行。然後,從第一個(最近的)時間戳開始,我檢查列L是否有1或0.如果找到1,我將位於條紋對象中的數字以名稱加1。如果我找到0,那麼條紋被破壞,我通過將streakEnded布爾值更改爲true來退出while循環。如果單元格爲空或值不是1或0,則不採取任何操作,並且循環繼續進行直至停止或沒有剩餘行。
最後,返回條紋對象。從那裏你可以在工作表中創建一個新頁面,或通過電子郵件發送結果,或者任何你可能想要做的事情。現在,我只是將對象記錄到腳本記錄器。您可以通過在腳本編輯器中選擇(查看>日誌)來查看結果。確保你已經突出顯示了單元格的範圍!
function streak() {
var activeRangeVals, allStreaks, columns;
// Get the active range as a 2-dimensional array of values
activeRangeVals = SpreadsheetApp.getActiveSheet().getActiveRange().getValues();
// Define which columns contain what data in the active Range
// There are better ways to do this (named ranges)
// but this was quickest for me.
columns = {
'name': 6, // G
'streak': 11, // L
'time': 0 // A
};
allStreaks = getStreaks(getEmployeeRowsObject(activeRangeVals));
Logger.log(allStreaks);
return allStreaks;
function getEmployeeRowsObject(data) {
// Create an empty object to hold employee data
var activeName, activeRow, employees = {}, i = 0;
// Iterate through the data by row and assign rows to employee object
// using employee names as the key
for(i = 0; i < data.length; i+= 1) {
// Assign the active row by copying from the array
activeRow = data[i].slice();
// Assign the active name based on info provided in the columns object
activeName = activeRow[columns['name']];
// If the employee is already defined on the object
if(employees[activeName] !== undefined) {
// Add the row to the stack
employees[activeName].push(activeRow);
// If not:
} else {
// Define a new array with the first row being the active row
employees[activeName] = [activeRow];
}
}
return employees;
}
function getStreaks(employees) {
var activeRow, activeStreak, i = 0, streaks = {}, streakEnded;
for(employee in employees) {
activeRow = employees[employee];
// Sort by timestamp in descending order (most recent first)
activeRow = activeRow.sort(function(a, b) {
return b[columns['time']].getTime() - a[columns['time']].getTime();
});
i = 0, streaks[employee] = 0, streakEnded = false;
while(i < activeRow.length && streakEnded === false) {
activeStreak = parseInt(activeRow[i][columns['streak']]);
if(activeStreak === 1) {
streaks[employee] += 1;
} else if(activeStreak === 0) {
streakEnded = true;
}
i += 1;
}
}
return streaks;
}
}
這應該是可能的公式。你能分享一些樣本數據嗎? – JPV