[英]Google Apps Script to protect range based on dates and don't protect a row if column is empty
[英]Google Apps Script to protect range based on dates
我試圖制作一個谷歌腳本來根據日期保護谷歌表格中的范圍
我想保護其日期為今天前 14 天的所有行
這是我到目前為止的代碼,
function ProtectEntradas() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheetEntradas = ss.getSheetByName('Entradas')
var dateRange = sheetEntradas.getRange(3, 1, sheetEntradas.getLastRow() - 2, 1);
var val = dateRange.getDisplayValues();
var date = new Date();
var protectDateRaw = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 14);
var protectDate = Utilities.formatDate(protectDateRaw, Session.getScriptTimeZone(), "dd-MMM-YY");
var protectRow;
//check if date is less than the current date
for (var i = 0; i < val.length; i++) {
if (val[i][0] >= protectDate) {
protectRow = i;
break;
}
}
var protection = sheetEntradas.getProtections(SpreadsheetApp.ProtectionType.RANGE);
//If protection exists, update else add new one.
if (protection.length > 0) {
var range = sheetEntradas.getRange(3, 1, protectRow, 10);
protection[0].setRange(range);
}
else {
sheetEntradas.getRange(3, 1, protectRow, 10).protect();
}
它正在做一些保護,但不是我期望的范圍
我做錯了什么?
然后我想讓觸發器每天運行,這樣它將動態地保護范圍
提前致謝
試試這個以正確比較日期(已修改 3 行代碼)
function ProtectEntradas() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheetEntradas = ss.getSheetByName('Entradas')
var dateRange = sheetEntradas.getRange(3, 1, sheetEntradas.getLastRow() - 2, 1);
// #### modification on how to fetch dates
var val = dateRange.getValues().map(d => Utilities.formatDate(d[0], Session.getScriptTimeZone(), "yyyy-MM-dd"))
var date = new Date();
var protectDateRaw = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 14);
// #### modification of the format
var protectDate = Utilities.formatDate(protectDateRaw, Session.getScriptTimeZone(), "yyyy-MM-dd");
var protectRow;
//check if date is less than the current date
for (var i = 0; i < val.length; i++) {
// #### modification
if (val[i] >= protectDate) {
protectRow = i;
break;
}
}
var protection = sheetEntradas.getProtections(SpreadsheetApp.ProtectionType.RANGE);
//If protection exists, update else add new one.
if (protection.length > 0) {
var range = sheetEntradas.getRange(3, 1, protectRow, 10);
protection[0].setRange(range);
}
else {
sheetEntradas.getRange(3, 1, protectRow, 10).protect();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.