Sheets script to create event in Calendar only creates event from last row in range

120 views
Skip to first unread message

James Mashiri

unread,
Apr 17, 2020, 10:15:05 AM4/17/20
to Google Apps Script Community
Hi,

I’m trying to use this script below to create a calendar event from dates and names entered in Sheets. I have one unresolved issue --the code runs successfully, but the issue is that from the given range (A1:C17) only the last row (17) turns into a calendar event. I just don’t get this. Checked so far: Sheets range and formats, all APIs and authorizations.

Here’s the code:
- - -
function CreateEvent () {
  var spreadsheet = SpreadsheetApp.getActiveSheet();
  var calendarId = 'primary'
  var eventCal = CalendarApp.getCalendarById(calendarId);  
  var signups = spreadsheet.getRange('A1:C17').getValues();
  
  for (x=0; x<signups.length; x++) {
    var shift = signups[x];
    var startTime = shift[0];
    var endTime = shift[1];
    var campaignname = shift[2];
  }
  eventCal.createEvent(campaignname, startTime, endTime);
}
- - -
Image: Sheets range A1:C17

sheets-a1-c17.png



Image: Calendar entry from May after running the script, all 16 entries before the last row are absent

only-name-q.png




I'm at a loss here. Please help! 

Kind regards,
//James

Alan Wells

unread,
Apr 17, 2020, 10:19:27 AM4/17/20
to Google Apps Script Community
This line:
eventCal.createEvent(campaignname, startTime, endTime);

Needs to be inside the "for" block.  It's outside of the loop.  That's why it's only executing once, and only creating one event.

James Mashiri

unread,
Apr 18, 2020, 6:21:43 AM4/18/20
to Google Apps Script Community
Thanks, Alan! That did it. Total blindness on my part. :)

CBM Services

unread,
Apr 18, 2020, 2:10:51 PM4/18/20
to google-apps-sc...@googlegroups.com
As a debugging technique it is sometimes useful to put tracepoints on key lines of code and then run the debugger. This lets you understand how the code is being run, you can also ser the value of local variables as they change and you could have understood easily that createEvent is only being called after the For loop had completed all its loops rather than every loop.

Sometimes the only way to find code problems is via the debugger.

From: James Mashiri
Sent: ‎2020-‎04-‎18 3:21 AM
To: Google Apps Script Community
Subject: [Apps-Script] Re: Sheets script to create event in Calendar onlycreates event from last row in range

--
You received this message because you are subscribed to the Google Groups "Google Apps Script Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-apps-script-c...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/google-apps-script-community/ced948fe-ad49-417d-ab52-fd1cc27e40b5%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages