I'm trying to figure out how to accomplish the following:
- Protect the sheet
- Iterate through each row
- If Column 1 contains a date that is > 7 days before the current date then
-
- unprotect column 3, 4, 5, 6 (within that row)
-
- Otherwise do nothing
I've reworked some other examples I found online, but I've been far from successful.
CodePudding user response:
Protects sheet unprotects rows > 7 days before the current date
function serveButNotProtect() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const osh = ss.getSheetByName("Sheet1");
const vs = sh.getRange(2, 1, sh.getLastRow() - 1, sh.getLastColumn()).getValues();
let p = sh.protect();
const a = [];
const dt = new Date();
const dtv = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate() - 7).valueOf();
vs.forEach((r, i) => {
let dv = new Date(r[0]);
if (dv > dtv) {
a.push(sh.getRange(i 2, 3, 1, 4))
}
});
if (a && a.length > 0) {
p.setUnprotectedRanges(a);
}
let b = p.getUnprotectedRanges().map(rg => [rg.getA1Notation()]).sort((a, b) => {
let va = parseInt(a[0].slice(1, a[0].indexOf(':')));
let vb = parseInt(b[0].slice(1, b[0].indexOf(':')));
return va - vb;
});
osh.clearContents();
osh.getRange(1, 1, b.length, b[0].length).setValues(b);
}
Sheet0:
A | B | C | D | E |
---|---|---|---|---|
COL1 | COL2 | COL3 | COL4 | COL5 |
9/1/2022 | 2 | 3 | 4 | 5 |
9/2/2022 | 3 | 4 | 5 | 6 |
9/3/2022 | 4 | 5 | 6 | 7 |
9/4/2022 | 5 | 6 | 7 | 8 |
9/5/2022 | 6 | 7 | 8 | 9 |
9/6/2022 | 7 | 8 | 9 | 10 |
9/7/2022 | 8 | 9 | 10 | 11 |
9/8/2022 | 9 | 10 | 11 | 12 |
9/9/2022 | 10 | 11 | 12 | 13 |
9/10/2022 | 11 | 12 | 13 | 14 |
9/11/2022 | 12 | 13 | 14 | 15 |
9/12/2022 | 13 | 14 | 15 | 16 |
9/13/2022 | 14 | 15 | 16 | 17 |
9/14/2022 | 15 | 16 | 17 | 18 |
9/15/2022 | 16 | 17 | 18 | 19 |
9/16/2022 | 17 | 18 | 19 | 20 |
9/17/2022 | 18 | 19 | 20 | 21 |
9/18/2022 | 19 | 20 | 21 | 22 |
9/19/2022 | 20 | 21 | 22 | 23 |
9/20/2022 | 21 | 22 | 23 | 24 |
Sheet1:
Unproted Ranges:
A |
---|
C8:F8 |
C9:F9 |
C10:F10 |
C11:F11 |
C12:F12 |
C13:F13 |
C14:F14 |
C15:F15 |
C16:F16 |
C17:F17 |
C18:F18 |
C19:F19 |
C20:F20 |
C21:F21 |