Below is a script I found and modified to track events by grabbing event information from our Calendar(s) and populating a spreadsheet (with mild reformatting) based on a selected date range.
Currently I have to manually change the dates within the script each week to get the events that I need. I would like to have a date picker pop up when I open a new sheet and have the selected dates input to the script, but I haven't been able to figure it out yet. Any help would be greatly appreciated.
function main(){
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
var header = [["Calendar Address", "Calendar Name", "Event Title", "Event Location", "Event Start", "Event Description" ]]
var range = sheet.getRange(1,1,1,6);
range.setValues(header);
sheet.setFrozenRows(1);
// var mycals is an array of google calendar id's; for gsuite, this is the email address of the user which calendar you will be viewing.
var mycals = ['9ss30f8ktuvbedmemka1ve8jss#group.calendar.google.com','8nmutqctujaetrnt5kfvi56kuo#group.calendar.google.com','ae1d2v0sqtktc183546u6cenps#group.calendar.google.com','ilr8eqk2l0ua9pr50t5307ivq8#group.calendar.google.com','5qubvv7mj5vjf7h1hhc23515h8#group.calendar.google.com', 'p2a9plkjd3vv9c87kb5kirapqk#group.calendar.google.com', '9ubfnjrb83tiqgi5l1nitaodp0#group.calendar.google.com', 'l6ouqfpktn05hstmokj8jhr1s4#group.calendar.google.com' ]
for (var j=0;j<mycals.length;j++) {
var cal = CalendarApp.getCalendarById(mycals[j]);
// error handling in case you don't have access to any specified calendar
if (!cal) { continue; }
var events = cal.getEvents(new Date("12/30/2019 00:00:00 EST"), new Date("1/3/2020 23:59:59 EST"));
for (var i=0;i<events.length;i++) {
var row = sheet.getLastRow() + 1
var details=[[events[i].getOriginalCalendarId(),,events[i].getTitle(), events[i].getLocation(), events[i].getStartTime(), events[i].getDescription()]];
var range=sheet.getRange(row,1,1,6);
range.setValues(details);
sheet.getRange(i+2, 5).setNumberFormat("mm/dd/yyyy h:mm Am/PM");
}
sheet.sort(1);
}
var lr= sheet.getLastRow();
for(var k=0+1; k<lr+1;k++){
var workingCell = sheet.getRange(k,1).getValue();
if(workingCell == '9ss30f8ktuvbedmemka1ve8jss#group.calendar.google.com'){
sheet.getRange(k,2).setValue("ATG_Cert");
}
else if(workingCell == '8nmutqctujaetrnt5kfvi56kuo#group.calendar.google.com'){
sheet.getRange(k,2).setValue("Functionality_Test");
}
else if(workingCell == 'ae1d2v0sqtktc183546u6cenps#group.calendar.google.com'){
sheet.getRange(k,2).setValue("Tightness_Test");
}
else if(workingCell == 'ilr8eqk2l0ua9pr50t5307ivq8#group.calendar.google.com'){
sheet.getRange(k,2).setValue("Pre_or_Post_Bury");
}
else if(workingCell == '5qubvv7mj5vjf7h1hhc23515h8#group.calendar.google.com'){
sheet.getRange(k,2).setValue("LLD");
}
else if(workingCell == 'p2a9plkjd3vv9c87kb5kirapqk#group.calendar.google.com'){
sheet.getRange(k,2).setValue("PMI");
}
else if(workingCell == '9ubfnjrb83tiqgi5l1nitaodp0#group.calendar.google.com'){
sheet.getRange(k,2).setValue("Stage_II_DeComm_Test");
}
else if(workingCell == 'l6ouqfpktn05hstmokj8jhr1s4#group.calendar.google.com'){
sheet.getRange(k,2).setValue("Other");
}
}
sheet.getRange(1,1,lr,6).setFontSize(14)
sheet.hideColumns(1);
sheet.autoResizeColumns(1, 6);
sheet.getRange(1, 1, lr, 6).setHorizontalAlignment("left")
}
Assuming that the rest of your code works then try this modification:
function main(){
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
var header = [["Calendar Address", "Calendar Name", "Event Title", "Event Location", "Event Start", "Event Description" ]]
var range = sheet.getRange(1,1,1,6);
range.setValues(header);
sheet.setFrozenRows(1);
var mycals = ['9ss30f8ktuvbedmemka1ve8jss#group.calendar.google.com','8nmutqctujaetrnt5kfvi56kuo#group.calendar.google.com','ae1d2v0sqtktc183546u6cenps#group.calendar.google.com','ilr8eqk2l0ua9pr50t5307ivq8#group.calendar.google.com','5qubvv7mj5vjf7h1hhc23515h8#group.calendar.google.com', 'p2a9plkjd3vv9c87kb5kirapqk#group.calendar.google.com', '9ubfnjrb83tiqgi5l1nitaodp0#group.calendar.google.com', 'l6ouqfpktn05hstmokj8jhr1s4#group.calendar.google.com' ]
var today=new Date();//added
var day=today.getDay();//added
var start=new Date(today.getFullYear(),today.getMonth(),today.getDate()-day+8);//added
var end=new Date(today.getFullYear(),today.getMonth(),today.getDate()-day+12);//added
for (var j=0;j<mycals.length;j++) {
var cal = CalendarApp.getCalendarById(mycals[j]);
// error handling in case you don't have access to any specified calendar
if (!cal) { continue; }
var events = cal.getEvents(start,end);
It looked like you want to view next weeks events between monday and friday. If not then make it a bit clearer what you are looking for.
Related
I'm having a hard time making a loop to extract more than one calendar to a google sheet. The calendars' IDs are in cell P1, the start date is in P7, and the end date is in P8.
The code works fine for one calendar, but when I try to add the j loop on more calendars, my extraction is empty. Can someone figure out what I'm doing wrong?
Thanks for your help.
Here is the code:
var sheet = SpreadsheetApp.getActiveSheet();
// Set filters
var startDate = sheet.getRange('p7').getValue();
var endDate = sheet.getRange('p8').getValue();
var mycal = sheet.getRange('p1').getValue().toString();
var cal = CalendarApp.getCalendarById(mycal);
// Create a header record on the current spreadsheet in cells A1:N1 - Match the number of entries in the "header=" to the last parameter
// of the getRange entry below
var header = [["Calendar Address", "Event Title", "Event Description", "Event Location", "Event Start", "Event End", "Calculated Duration", "Visibility", "Date Created", "Last Updated", "MyStatus", "Created By", "All Day Event", "Recurring Event"]]
var range = sheet.getRange(1,1,1,14);
range.setValues(header);
var row=2
for (var j = 0; j< mycal.lengh; j++){
//here we do the things we do once per calander
var cal = CalendarApp.getCalendarById(mycal[j]);
var events = cal.getEvents(startDate, endDate);
// Loop through all calendar events found and write them out starting on calulated ROW 2 (i+2)
for (var i=0;i<events.length;i++) {
var row=i+2;
var myformula_placeholder = '';
var details=[[mycal,events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), events[i].getStartTime(), events[i].getEndTime(), myformula_placeholder, ('' + events[i].getVisibility()), events[i]. getDateCreated(), events[i].getLastUpdated(), events[i].getMyStatus(), events[i].getCreators(), events[i].isAllDayEvent(), events[i].isRecurringEvent()]];
var range=sheet.getRange(row,1,1,14);
range.setValues(details);
var cell=sheet.getRange(row,7);
cell.setFormula('=(HOUR(F' +row+ ')+(MINUTE(F' +row+ ')/60))-(HOUR(E' +row+ ')+(MINUTE(E' +row+ ')/60))');
cell.setNumberFormat('.00');
row++;
}
}
}
As #Cooper mentioned, lengh is not an attribute. I made that correction and other changes to the script. Also, I created another sheet where I have a list of calendar ID's, the startDate and endDate. See the script below, I added some comments to explain the changes I made. Make sure to change ranges based on where you have your data.
function calendarFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2"); //Sheet name where you will have the list of calendar ID's, startDate and endDate
sheet.clear() // If you'll be runnning the script several times, the data will be duplicated so I added this line to clear the sheet before adding the data
// other option would be to create a script to check if data already exists before adding it to the sheet
// Set filters
var startDate = sheet2.getRange('B1').getValue(); //Range for startDate
var endDate = sheet2.getRange('B2').getValue(); //Range for endDate
var users = sheet2.getRange('A1:A').getValues(); //Range where you have the calendar ID's
// Create a header record on the current spreadsheet in cells A1:N1 - Match the number of entries in the "header=" to the last parameter
// of the getRange entry below
var header = [["Calendar Address", "Event Title", "Event Description", "Event Location", "Event Start", "Event End", "Calculated Duration", "Visibility", "Date Created", "Last Updated","MyStatus", "Created By", "All Day Event", "Recurring Event"]]
var range = sheet.getRange(1,1,1,14);
range.setValues(header);
for (var j = 0; j< users.length; j++){
//here we do the things we do once per calander
if (users[j] == ""){
break;
}
else{
var cal = CalendarApp.getCalendarById(users[j]);
var events = cal.getEvents(startDate, endDate);
// Loop through all calendar events found and write them out starting on the next empty row
for (var i=0;i<events.length;i++) {
var myformula_placeholder = '';
var details=[
[users[j].toString(),events[i].getTitle(), events[i].getDescription(), events[i].getLocation(), events[i].getStartTime(), events[i].getEndTime(),
myformula_placeholder, ('' + events[i].getVisibility()), events[i].getDateCreated(), events[i].getLastUpdated(), events[i].getMyStatus(),
events[i].getCreators().toString(), events[i].isAllDayEvent(), events[i].isRecurringEvent()]
];
var lastRow = sheet.getLastRow()+1;
var range=sheet.getRange(lastRow,1,1,14);
range.setValues(details);
var cell=sheet.getRange(lastRow,7);
cell.setFormula('=(HOUR(F' +lastRow+ ')+(MINUTE(F' +lastRow+ ')/60))-(HOUR(E' +lastRow+ ')+(MINUTE(E' +lastRow+ ')/60))');
cell.setNumberFormat('.00');
}
}
}
}
Thanks to the help of this amazing community, I was able to have a script that run so much faster.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Extraction 8 - Calendrier");
var sheet2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Id Calendriers - Dates Debut et Fin"); //Sheet name where you will have the list of calendar ID's, startDate and endDate
sheet.clear() // If you'll be runnning the script several times, the data will be duplicated so I added this line to clear the sheet before adding the data
// other option would be to create a script to check if data already exists before adding it to the sheet
// Set filters
var startDate = sheet2.getRange('k15').getValue(); //Range for startDate
var endDate = sheet2.getRange('k16').getValue(); //Range for endDate
var users = sheet2.getRange('b3:B').getValues(); //Range where you have the calendar ID's
// Create a header record on the current spreadsheet in cells A1:N1 - Match the number of entries in the "header=" to the last parameter
// of the getRange entry below
const data = []
const formulas = [];
const headers = [["Titre", "Description", "Location", "Début", "Fin", "Heures effectives","Extraction 2","Extraction 3","Heures Planifiées", "Vacances", "Maladie","Congé légal", "Absence"]]
for (var j = 0; j< users.length; j++){
//here we do the things we do once per calander
if (users[j] == ""){
break;
}
else{
var cal = CalendarApp.getCalendarById(users[j]);
var events = cal.getEvents(startDate, endDate);
var lastRow = sheet.getLastRow()+8;
// Loop through all calendar events found and write them out starting on the next empty row
for (var i = 0; i < events.length; i++) {
var details=
[
events[i].getTitle(),
events[i].getDescription(),
events[i].getLocation(),
events[i].getStartTime(),
events[i].getEndTime()
];
data.push(details);
const rowFormulas =
[
'=(HOUR(RIGHT(b' +lastRow+';5))+(MINUTE(RIGHT(b' +lastRow+ ';5))/60))-(HOUR(LEFT(b' +lastRow+ ';5))+(MINUTE(LEFT(b' +lastRow+ ';5))/60))',
'=IFERROR(TEXT(INDEX(SPLIT(A'+lastRow+';" ");2);"hh:mm");"")',
'=IFERROR(TEXT(INDEX(SPLIT(A'+lastRow+';" ");3);"hh:mm");"")',
'=IF(OR(G'+lastRow+'="Maladie";G'+lastRow+'="Congé";G'+lastRow+'="Absence";G'+lastRow+'="00:00";G'+lastRow+'="Vacances");0;(HOUR(H'+lastRow+')+(MINUTE(H'+lastRow+')/60))-(HOUR(G'+lastRow+')+(MINUTE(G'+lastRow+')/60)))',
'=IF(IFNA(VLOOKUP(D'+lastRow+'; feries;1;FALSE);1)<>1;0;IF(AND(G'+lastRow+'="00:00";H'+lastRow+'="Vacances");0.5;IF(G'+lastRow+'="Vacances";1;0)))',
'=IF(G'+lastRow+'="Maladie";1;0)',
'=IF(G'+lastRow+'="Congé";1;0)',
'=IF(G'+lastRow+'="Absence";1;0)'
]
formulas.push(rowFormulas)
lastRow=lastRow+1
}
}
}
sheet.getRange(7,1,headers.length, headers[0].length).setValues(headers)
sheet.getRange(8,1,data.length,data[0].length).setValues(data);
sheet.getRange(8,data[0].length + 1,formulas.length, formulas[0].length).setFormulas(formulas);
sheet.getRange(8,6,sheet.getLastRow()).setNumberFormat('.00');
}```
I don't know much about programming but I created a script for one of my spreadsheets which worked very well a few months ago.
But lately it is impracticable to use any script, however simple it may be. Sometimes it runs perfectly in 1 or 2 seconds and most of the time it just times out and fails. 90% of executions result in "timed out".
In summary, the function must be executed every time column B or C of the spreadsheet is edited. For this I used the function OnEdit ().
When column B is edited, the date and time is inserted in column D in the respective line where the change occurred.
When column C is edited, the date and time is inserted in column E in the respective line where the change occurred.
Here is the code:
function onEdit(e)
{
var column = e.range.getColumn();
var aba = e.source.getActiveSheet().getName();
if (column == 2 && aba == "Controle")
{
var ss = SpreadsheetApp.getActiveSheet();
var cell = ss.getActiveCell();
if(cell.getValue() != "")
{
var add = cell.offset(0, 2);
var data = new Date();
data = Utilities.formatDate(data, "GMT-03:00","dd/MM/yyyy' 'HH:mm' '");
add.setValue(data);
}
else
{
var add = cell.offset(0, 2);
var data = new Date();
data = "";
add.setValue(data);
}
}
if (column == 3 && aba == "Controle")
{
var ss = SpreadsheetApp.getActiveSheet();
var cell = ss.getActiveCell();
if(cell.getValue() == true)
{
var add = cell.offset(0, 2);
var data = new Date();
data = Utilities.formatDate(data, "GMT-03:00","dd/MM/yyyy' 'HH:mm' '");
add.setValue(data);
}
else
{
var add = cell.offset(0, 2);
var data = new Date();
data = "";
add.setValue(data);
}
}
}
Even super simple recorded macros like applying a filter are showing this problem.
I would like to know if there is something that can be done in the code to make it more efficient to solve this problem or if the timeout problem reached is related to something else.
Thanks
Try this:
function onEdit(e) {
const sh=e.range.getSheet();
if(sh.getName()=='Controle' && e.range.columnStart>1 && e.range.columnStart<4) {
if(e.range.columnStart==2) {
if(e.value='') {
e.range.offset(0,2).setValue(Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yyyy' 'HH:mm' '"));
}else{
e.range.offset(0,2).setValue(new Date());
}
}
if(e.range.columnStart==3) {
if(e.value==true) {
e.range.offset(0,2).setValue(Utilities.formatDate(new Date(), "GMT-3", "dd/MM/yyyy' 'HH:mm' '"));
}else{
e.range.offset(0,2).setValue(new Date());
}
}
}
}
Based on your logs, your script is reaching quota for exceeding maximum execution time, although it is also possible from your scenario to have more than 30 simultaneous executions, which will make the script fail to run too.
One workaround, as Cooper have said in the comments, is to implement a lock on parts of the script, especially on sections that make changes to the spreadsheet, to make subsequent executions wait on one script to complete.
Sample code:
function onEdit(e)
{
var column = e.range.getColumn();
var aba = e.source.getActiveSheet().getName();
var lock = LockService.getScriptLock();
try { lock.waitLock(10000); } // wait 10 sec
if (column == 2 && aba == "Controle")
{
var ss = SpreadsheetApp.getActiveSheet();
var cell = ss.getActiveCell();
if(cell.getValue() != "")
{
var add = cell.offset(0, 2);
var data = new Date();
data = Utilities.formatDate(data, "GMT-03:00","dd/MM/yyyy' 'HH:mm' '");
add.setValue(data);
}
else
{
var add = cell.offset(0, 2);
var data = new Date();
data = "";
add.setValue(data);
}
}
if (column == 3 && aba == "Controle")
{
var ss = SpreadsheetApp.getActiveSheet();
var cell = ss.getActiveCell();
if(cell.getValue() == true)
{
var add = cell.offset(0, 2);
var data = new Date();
data = Utilities.formatDate(data, "GMT-03:00","dd/MM/yyyy' 'HH:mm' '");
add.setValue(data);
}
else
{
var add = cell.offset(0, 2);
var data = new Date();
data = "";
add.setValue(data);
}
}
SpreadsheetApp.flush(); // applies all pending spreadsheet changes
lock.releaseLock();
}
References:
Quotas for Google Services
Class Lock
I'm trying to develop a simple script to create a log table to show certain information when a checkbox is marked on one of the Sheets.
The script works correctly (it does what it needs to do) but sometimes works slow. If more than one user 'edits' the Sheet at the same time some entries get lost because the last edit overwrites the previous one. I need to optimize the script as much as possible to avoid losing information.
I think there are 2 possible ways to do it. One is using a function to identify the next available row and the other one is using a countA function within the sheet and get the value from the code (...getRange('whatever').getValue()).
Both of them turned to be slow, so I guess the issue is elsewhere.
I have also tried to use onEdit(e) and getting the active range by e.range but it is also too slow.
Please, find below the code.
function onEdit() {
var ss = SpreadsheetApp.getActive();
var user = Session.getActiveUser().getEmail();
var activeCell = ss.getActiveRange();
var sheet = activeCell.getSheet();
var row = activeCell.getRow();
var column = activeCell.getColumn();
var activeCellValue = activeCell.getValue();
if(!isSupervisor(user) && activeCellValue == true && sheet.getName() != "Activities" && sheet.getName() != "Edit Log" && row >= 10 && column >= 2 && column <= 26 && column % 2 != 0){
var editLog = ss.getSheetByName("Edit Log");
var nextRow = 4 + editLog.getRange('P1').getValue();
var date = new Date();
var language = sheet.getRange(4, column - 1).getValue();
var assignedTo = sheet.getRange(3, column - 1).getValue();
var startHour = sheet.getRange(row, 1).getValue();
var startHourHour = sheet.getRange(row, 27).getValue();
var startHourMinutes = sheet.getRange(row, 28).getValue();
var activity = sheet.getRange(row, column - 1).getValue();
var note = activeCell.getNote();
var generatingID = sheet.getName()+"_"+language+"_"+activity+"_"+startHourHour;
//var shortID = language+"_"+activity+"_"+startHour;
if(!isAlreadyAdded(generatingID, editLog.getRange("A4:A").getValues())) {
editLog.getRange("B1").setValue("Not added");
editLog.getRange("B2").setValue(generatingID);
editLog.getRange(nextRow, 1).setValue(generatingID);
editLog.getRange(nextRow, 3).setValue(date);
editLog.getRange(nextRow, 4).setValue(user);
editLog.getRange(nextRow, 5).setValue(sheet.getName());
editLog.getRange(nextRow, 6).setValue(activeCellValue);
editLog.getRange(nextRow, 7).setValue(language);
editLog.getRange(nextRow, 8).setValue(activity);
editLog.getRange(nextRow, 9).setValue(assignedTo);
editLog.getRange(nextRow, 10).setValue(startHour);
editLog.getRange(nextRow, 13).setValue(note);
} else {
editLog.getRange("B1").setValue("Already added");
editLog.getRange("B2").setValue(generatingID);
}
}
}
function isAlreadyAdded(generatingID, values) {
for(var i = 0; i < values.length; i++) {
if(values[i] == generatingID) {
return true;
}
}
return false;
}
function getFirstEmptyRow(data) {
for(var i = 0; i < data.length; i++) {
if(data[i][0] == null || data[i][0] == '') {
return i;
}
}
}
function isSupervisor(user) {
var supervisors = getSupervisors();
for(var i = 0; i < supervisors.length; i++) {
if(user == supervisors[i]) {
return true;
}
}
return false;
}
function getSupervisors() {
var supervisors = [];
//real values are hidden due to confidential information
supervisors.push("???");
supervisors.push("???");
supervisors.push("???");
supervisors.push("???");
supervisors.push("???");
supervisors.push("???");
supervisors.push("???");
supervisors.push("???");
return supervisors;
}
As previously mentioned, I need to make this script as fast as possible. I can't lose any entry due to the slowness of the script. Do you have any suggestion?
Thanks for your help :)
I'm working on a spreadsheet for my department to create, edit, and delete work assignments to a google calendar. It's been quite a while since I did any actual coding, so I've been doing a lot of trial and error and referring to the Google App Script and Calendar references. I've finally gotten to the point where I can create the events; however, when I am testing my function to delete events, I've discovered that the event on row two, deletes the event on row three, and when I try to delete the event on row three, I get a "cannot call method deleteEvent" error. I've tried looking through various sites for similar situations and have not been successful. Any help walking me through the error in my code issue would be greatly appreciated. I'm also attempting to attach a link for a video of the spreadsheet as the script is running here
// Adds the custom menu to the active spreadsheet.
function onOpen() {
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var menuEntries = [
{
name: "Create New Events",
functionName: "createCalEvent"
}, {
name: "Update Existing Events",
functionName: "updateCalEvent"
}, {
name: "Delete Existing Events",
functionName: "deleteCalEvent"
}
];
spreadsheet.addMenu('Calendar Options', menuEntries);
}
// Event Status --> Assist in Triggering Update/Delete Functions
var delConfirmed = 'Event Created';
var updateConfirmed = 'Event Updated';
var eventCreate = 'Event Deleted';
function createCalEvent(){
var calSheet = SpreadsheetApp.getActiveSheet();
var dataRange = calSheet.getRange('$A2:$J');
var data = dataRange.getValues();
for (var i = 0; i < data.length; i++) {
var row = data[i];
var calDate = row[1]; // COL A
var calTitle = row[5]; // COL F
var calGuests = row[6]; // COL G
var calEType = row[7]; // COL H
var calID = row[8]; // COL I
var calStatus = row[9]; // COL J
// If there is a date and both the Event Type (Adjust/Delete) and Status are blank then Create the Calendar Event
if(calDate !=='' && calEType == '' && calStatus == ''){
var calEvent = CalendarApp
.getCalendarById('envysion.com_kmfeb8mqmlv4j9k34l37q7fv3k#group.calendar.google.com')
.createAllDayEvent(calTitle, new Date(calDate),{guests:calGuests});
// Update the Status Column
SpreadsheetApp.getActiveSheet().getRange(i+2, 10).setValue('Event Created');
var newEvent = calEvent.getId();
// Add the Event ID to the Event ID Column
SpreadsheetApp.getActiveSheet().getRange(i+2,9).setValue(newEvent);
Logger.log('Event ID: ' + newEvent + ' Title: ' + calEvent.getTitle() + 'Guests: ' + calEvent.getGuestList());
}
}
}
function deleteCalEvent()
{
// Get range of dates to delete
var fromDate = new Date(2019,3,1);
var toDate = new Date(2019,4,1);
// Get Calendar Events
var calendar = CalendarApp.getCalendarById('envysion.com_kmfeb8mqmlv4j9k34l37q7fv3k#group.calendar.google.com')
var events = calendar.getEvents(fromDate, toDate);
// Get Spreadsheet Details
var calSheet = SpreadsheetApp.getActiveSheet();
var dataRange = calSheet.getRange('$A2:$J');
var data = dataRange.getValues();
for (var i = 0; i < data.length; i++) {
var row = data[i];
var calDate = row[1];
var calTitle = row[5];
var calGuests = row[6];
var calEType = row[7];
var calID = row[8];
var calStatus = row[9];
// Check if the Type column is set to Delete and if the event hasn't already been deleted
if(calEType == 'Delete' && calStatus !== 'Event Deleted'){
events[i].deleteEvent();
SpreadsheetApp.getActiveSheet().getRange(i+2, 10).setValue('Event Deleted');
SpreadsheetApp.getActiveSheet().getRange(i+2, 9).setValue('');
}
}
}
It seems you need do something like this
if(calEType == 'Delete' && calStatus !== 'Event Deleted'){
var _event_ = calendar.getEventById(calStatus);
if(_event_){
_event_.deleteEvent();
SpreadsheetApp.getActiveSheet().getRange(i+2, 10).setValue('Event Deleted');
SpreadsheetApp.getActiveSheet().getRange(i+2, 9).setValue('');
}
}
This is because you may have a different number of events in the calendar and in the sheet.
This script is working cool for me.. Rather than filtering the changelog sheet to get my data I want the script to only record the changes in a specific range lets say 'A2:E150'. With my minimal knowledge in coding I tried inserting the .getrange() thing at few places but to no luck..
So hoping someone can help me out on where to define the range exactly in the script
Code:
function onEdit() {
var sheetsToWatch = ['outcome overview', 'Sheet1', 'Another sheet'];
// name of the sheet where the changelog is stored
var changelogSheetName = "Changelog";
var timestamp = new Date(new Date().setHours(0,0,0,0));
var ss = SpreadsheetApp.getActiveSpreadsheet().getRange('A2:A');
var sheet = ss.getActiveSheet();
var cell = sheet.getActiveCell();
var sheetName = sheet.getName();
var email = Session.getActiveUser().getEmail();
var email2 = Session.getEffectiveUser().getEmail();
// if it is the changelog sheet that is being edited, do not record the change
if (sheetName == changelogSheetName) return;
// if the sheet name does not appear in sheetsToWatch, do not record the change
var matchFound = false;
for (var i = 0; i < sheetsToWatch.length; i++) {
if (sheetName.match(sheetsToWatch[i])) matchFound = true;
}
if (!matchFound) return;
var columnLabel = sheet.getRange(/* row 1 */ 1, cell.getColumn()).getValue();
var rowLabel = sheet.getRange(cell.getRow(), /* column A */ 1).getValue();
var changelogSheet = ss.getSheetByName(changelogSheetName);
if (!changelogSheet) {
// no changelog sheet found, create it as the last sheet in the spreadsheet
changelogSheet = ss.insertSheet(changelogSheetName, ss.getNumSheets());
// Utilities.sleep(2000); // give time for the new sheet to render before going back
// ss.setActiveSheet(sheet);
changelogSheet.appendRow(["Timestamp", "Sheet name", "Cell address", "Column label", "Row label", "Value entered","email", "email2"]);
changelogSheet.setFrozenRows(1);
}
changelogSheet.appendRow([timestamp, sheetName, cell.getA1Notation(), columnLabel, rowLabel, cell.getValue(), email, email2]);
}
You should be able to record changes within a given range by testing if the "ActiveCell" (sheet.getActiveCell()) is within a specified range.
To test if the ActiveCell is in a given Range, I would do something like this:
var cell = sheet.getActiveCell();
// .getColumn returns an integer, where A=1, B=2, etc.
if (cell.getColumn() < 6 && cell.getRow() > 1 && cell.getRow() < 151) {
//execute script
} else {
return
}
I would also recommend removing .getRange('A2:A') from the declaration of your variable ss.