Rcoster
Rcoster

Reputation: 3210

Writing an array in Google Spreadsheets

I'm trying to learn javascript, so I decided to code a script in Google Apss Script to list all emails with attachment. Until now, I have this code:

function listaAnexos() {
  // var doc = DocumentApp.create('Relatório do Gmail V2');
  var plan = SpreadsheetApp.create('Relatorio Gmail');
  var conversas = GmailApp.search('has:attachment', 0, 10)
  var tamfinal = 0;
  if (conversas.length > 0) {
    var tam = 0
    var emails = GmailApp.getMessagesForThreads(conversas);
    var cont = 0;
    for (var i = 0 ; i < emails.length; i++) {
      for (var j = 0; j < emails[i].length; j++) {
        var anexos = emails[i][j].getAttachments();
        for (var k = 0; k < anexos.length; k++) {
          var tam = tam + anexos[k].getSize();
        }
      }
      var msginicial = conversas[i].getMessages()[0];
      if (tam > 0) {
        val = [i,  msginicial.getSubject(), tam];
        planRange = plan.getRange('A1:C1');
        planRange.setValue(val);
        // doc.getBody().appendParagraph('A conversa "' + msginicial.getSubject() + '" possui ' + tam + 'bytes em anexos.');
      }
      var tamfinal = tamfinal + tam;
      var tam = 0;
    }
  }
}
listaAnexos();

It works, but with 2 problems:

1) It writes the three val values at A1, B1 and C1. But I want to write i in A1, msginicial.getSubject() in B1 and tam in C1.

2) How can I change the range interactively? Write the first email in A1:C1, the second in A2:C2 ...

I know that are 2 very basic questions, but didn't found on google :(

Upvotes: 0

Views: 100

Answers (1)

Mogsdad
Mogsdad

Reputation: 45750

Problem 1: Make sure you use the right method for the range. You've used Range.setValue() which accepts a value as input, and modifies the content of the range using that one value. You should have used Range.setValues(), which expects an array and modifies a range of the same dimensions as the array. (The array must be a two-dimensional array, even if you're only touching one row.)

    val = [[i,  msginicial.getSubject(), tam]];
    planRange = plan.getRange('A1:C1');
    planRange.setValues(val);

Problem 2: (I assume you mean 'programmatically' or 'automatically', not 'interactively'.) You can either use row and column numbers in a loop say, with getRange(row, column, numRows, numColumns), or build the range string using javascript string methods.

Upvotes: 1

Related Questions