My answer is similar to what Cooper provided so I'll have this posted instead to help your sheet maintained properly.
I added a behaviour during onEdit()
in which when a user added an existing set of start and end date in the sheet, the recently added/edited row is automatically deleted.
This can reduce the number of calls to calendar at the expense of constantly checking sheets during edits.
Feel free to use the code below
function onEdit(e) {
var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
var currentSheet = SpreadsheetApp.getActiveSheet();
var cell = currentSheet.getActiveCell();
var cellValue = cell.getValue();
var date, dates, occurences, limit;
// newly added date in active sheet
if (cell.getColumn() == 2) {
date = [cellValue, cell.offset(0, 1).getValue()];
}
else if (cell.getColumn() == 3) {
date = [cell.offset(0, -1).getValue(), cellValue];
}
// traverse other sheets
sheets.forEach(function(sheet){
var sheetName = sheet.getName();
// dates from other sheets
dates = sheet.getRange(2, 2, sheet.getLastRow(), 2).getValues();
occurences = 0;
// check if dates in other sheets have the newly added date
for(var index in dates){
if(JSON.stringify(dates[index]) === JSON.stringify(date)) {
// increment if found
occurences++;
}
}
if(sheet.getName() != currentSheet.getName()) {
// should not occur in other sheets
limit = 0;
}
else {
// should occur at most once in the active sheet
limit = 1;
}
// if date was found more than the limit
if (occurences > limit) {
// prompt user that the newly added date is present in other sheets
SpreadsheetApp.getUi().alert('WARNING!: Dates are already booked in ' + sheetName + '. Deleting newly added event.');
// delete newly added date
currentSheet.deleteRow(cell.getRow());
}
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…