Martimus
Martimus

Reputation: 27

Exception error with 2D array size in Google Apps Script

The exception is:

The number of columns in the data does not match the number of columns in the range. The data has 0 but the range has 3.

I want to populate a google spreadsheet with the three columns and the length of the threads. When I debug the program the arrays are empty. Is there another method that should be used to create a 2D array that can be used with the getrange?

function TheaThreads(){
 var SS =SpreadsheetApp.getActiveSpreadsheet();
 var ThreadSheet = SS.getSheetByName("Threads");
 var threads = GmailApp.getInboxThreads();
 var csNames = new Array();

   for (var i=0; i < threads.length; i++) {
    for (var j = 0; j < 
     threads[i].getMessages().length; j++){
  
     var message = threads[i].getMessages()[j],
     label = threads[i].getLabels(),
     ident = message.getId(),
     emailfrom = message.getFrom();
  
  //remove the name that comes with the email and pops the > at the end and store into str
   
      var str = emailfrom.split("<").pop();
      str=str.replace(">",'');
  // Label empty labels with "No Label"
      if(label==null|| label== undefined|| 
       label.length==0){
       label="No Label";
      }
     }

  //Push the ID, Label and FromEmail into 2D array
  
    csNames[j] = new Array();
    csNames[j][0]= ident;
    csNames[j][1]= label;
    csNames[j][2]=str; 
    Logger.log(csNames[j]);

    ThreadSheet.getRange(2, 1, csNames.length, 
    csNames[j].length).setValues(csNames);

Upvotes: 1

Views: 118

Answers (1)

Cooper
Cooper

Reputation: 64062

This runs for me:

 function TheaThreads() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName("Sheet1");//changed
  var threads = GmailApp.getInboxThreads();
  var csNames = [['id','label','from']];//changed

  for (var i = 0; i < threads.length; i++) {
    for (var j = 0; j < threads[i].getMessages().length; j++) {
      var message = threads[i].getMessages()[j],
        label = threads[i].getLabels().map(l=>{return l.getName()}).join(','),
        ident = message.getId(),
        emailfrom = message.getFrom();//changed
      var str = emailfrom.split("<").pop();
      str = str.replace(">", '');
      if (label == null || label == undefined ||
        label.length == 0) {
        label = "No Label";
      }
    }
    csNames.push([ident,label,str]);
  }
  sh.getRange(1, 1, csNames.length, csNames[0].length).setValues(csNames);//moved
}

Upvotes: 1

Related Questions