我创建了一个脚本,从谷歌工作表复制事件并将其广告到日历中。每次更新工作表时,日历都需要更新。问题是每次脚本运行时事件都会重复,我不想重复。代码如下:
function copyCalender() {
var spreadsheet = SpreadsheetApp.getActiveSheet()
var eventCal = CalendarApp.getCalendarById("[email protected]");
var signups = spreadsheet.getDataRange().getValues();
for(x=0;x<signups.length;x++) {
var notAvailable=signups[x]
var busy = notAvailable[0]
var startTime = notAvailable[1]
var endTime = notAvailable [2]
eventCal.createEvent(busy, startTime, endTime);
}
}
我希望代码不会重复事件而只复制新事件。
您的事件正在重复,因为您没有任何选项来对比事件是否已为提供的数据创建。我所做的是使用“辅助列”来存储 EventID 并将其用作标识符。这可能不是最优雅的解决方案,但这就是我所做的。不要忘记您可以隐藏“帮助器列”。
function createEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('SheetX');
var eventCal = CalendarApp.getCalendarById("[email protected]");
var signups = ss.getDataRange().getValues();
console.log(signups)
for (x = 1; x < signups.length; x++) {
var notAvailable = signups[x];
var busy = notAvailable[1];
var startTime = new Date(notAvailable[2]);
var endTime = new Date(notAvailable[3]);
var eventId = notAvailable[4];
var helperColumn = notAvailable[5];
if (!helperColumn) {
if (eventId) {
// Try to get the event by ID
try {
var event = eventCal.getEventById(eventId);
if (event) {
// Event already exists
event.setTitle(busy);
event.setTime(startTime, endTime);
} else {
// Create a new event if not found
event = eventCal.createEvent(busy, startTime, endTime);
ss.getRange(x + 1, 5).setValue(event.getId()); // Store event ID
}
} catch (e) {
// Event not found, we need to create it
event = eventCal.createEvent(busy, startTime, endTime);
ss.getRange(x + 1, 4).setValue(event.getId()); // Store event ID
}
} else {
// Create a new event if no event ID
var event = eventCal.createEvent(busy, startTime, endTime);
ss.getRange(x + 1, 5).setValue(event.getId()); // Store event ID
}
// Mark the row as processed in the helper column
ss.getRange(x + 1, 6).setValue("Event Created");
}
}
}