Shihan Khan
Shihan Khan

Reputation: 2188

setValues not working for arrays in Google Apps Script

I'm new to Google Apps Script and I want to make a script for spreadsheet where I want to store the email addresses of others that has sent me, to my spreadsheet. I push all the emails to an array and use that array to store in the spreadsheet.

For some reason, .setValues() is not working though I see all the emails through log. Here are my codes:

      var n=threads.length;
      var messages=thread.getMessages();
      var getfrom = 0;
      var allMails = [];
      for (var i=0; i<n; i++)
      {
         for (var j=0; j<messages.length; j++)
         {
            var message=messages[j];
            getfrom = message.getFrom();
            var first_name = getfrom.substring(0, getfrom.indexOf(" "));
            var last_name = getfrom.substring(getfrom.indexOf(" ")+1, getfrom.indexOf(" <"));
            var email_address = 0;
            if (first_name == '' && last_name == '')
            {
               email_address = getfrom;
            } else {
               email_address = getfrom.substring(getfrom.indexOf("<")+1, getfrom.indexOf(">"));
            }
          }
          allMails.push(email_address);
      }
      Logger.log(allMails);
      sheet1.getRange(2, 3, n, 1).setValues(allMails);
      Browser.msgBox("Operation complete");

How can I set all the values from the allMails[] array in my spreadsheet?

Upvotes: 2

Views: 1135

Answers (1)

Robin Gertenbach
Robin Gertenbach

Reputation: 10806

setValues() needs a "two dimensional" array, as in an array of equal length arrays.

You want to supply the emails to the sheet as separate rows so try pushing the email addresses as single element arrays to the array, i.e.:

allMails.push([email_address]);

Upvotes: 2

Related Questions