Lucas Martins
Lucas Martins

Reputation: 13

Why does my loop doesn't work on GoogleSheets?

So, I've been trying to do this: https://wafflebytes.blogspot.com/2017/06/google-script-create-calendar-events.html

I've pasted this code, and it worked quite nicely (the only downside is that the eventID always took the last column, instead of the one I choose).

Then I wrote this code:

function createCalendar() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var calendar = CalendarApp.getCalendarById('YES MY ID IS HERE BUT I REMOVED TO POST');
 
  var startRow = 2;  
  var numRows = sheet.getLastRow();   
  var numColumns = sheet.getLastColumn();
 
  var dataRange = sheet.getRange(startRow, 1, numRows-1, numColumns);
  var data = dataRange.getValues();
 
  var complete = "on";
  
  
  for (var i = 0; i < data.length; ++i) {
    var row = data[i];
    var aplicador = row[2];
    var data = new Date(row[9]);
    var datafim = new Date(row[11]);
    var eventID = row[22];  
    
    if (eventID != complete) {
      var currentCell = sheet.getRange(startRow + i, numColumns);
      calendar.createEvent(aplicador, data, datafim);
    
      currentCell.setValue(complete);
    }
   
  }
  console.log(data.length)
}

which is exactly the same code, except I changed some variables. And it doesn't work. It does well on the first line, but the loop doesn't happen.

Why is that?

Upvotes: 1

Views: 42

Answers (1)

Cooper
Cooper

Reputation: 64140

You declared data twice once inside the loop and once for all of the data on the spreadsheet.

Try it this way:

function createCalendar() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getActiveSheet();
  const calendar=CalendarApp.getCalendarById('YES MY ID IS HERE BUT I REMOVED TO POST');
  const shsr=2;
  const rg=sh.getRange(shsr,1,sh.getLastRow()-shsr+1,sh.getLastColumn());
  var data=rg.getValues();
  const complete="on";
  const lc=sh.getLastColumn();
  data.forEach(function(r,i){
    let aplicador=r[2]
    let dts=new Date(r[9])
    let dte=new Date(r[11]);
    let eventId=r[22];
    if(eventId!="on") {
      calendar.createEvent(aplicador,dts, dte);
      sh.getRange(shsr+i,22).setValue("on")+
    }
  });
}

Upvotes: 1

Related Questions