0

I wrote a script to display a list of names and folder IDs.

The script that I wrote like this:

function listFolders() {

var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange('A2:B').clear();
  //sheet.appendRow(["Name", "Folder-Id"]);

var folderID = DriveApp.getFolderById("1Hp_dM8WR0mGDT5q-a-VS-VVtl5dNCLfe");
var contents = folderID.getFolders();

var cnt = 0;
var lFolder;

while (contents.hasNext()) {
    var lFolder = contents.next();
    cnt++;

       data = [
            lFolder.getName(),
            lFolder.getId(),
        ];

         sheet.getRange(2, 1, data.length, data[0].length).setValues(data); //modified
    };
};

I want to add new data in column C. After I fill in a text in column C, then I run the script. But the second row is empty.

enter image description here

0

1 Answer 1

0

Regarding the rev 2 of the question

I don't think that the modified code line produce the result of the previous code and it's shown in the image because it writes data over and over the same range.

If you will go to use that code line then the first argument should be a variable corresponding to the row where the data will be written.

I reiterate that a better practices is to avoid the use of Google Apps Script methods inside a loop, instead create an array that hold all the values to be added to the sheet then add them on a single statement (it's implicit that it will be out of any loop).

About the rev 1 of the question

appendRow(rowContent) adds the rowContent to the first empty row, so if you will be writing data on column C, instead of it use setValues(values).

It's worth to note that Google Apps Script methods are slow so it's advisable whenever is possible to avoid their use on loops. To do this use your loop to create an array of values, then on a single statement pass the array to the spreadsheet.

Related

7
  • I've changed the script to something like this, hastebin.com/oxabijunux.js but it's still an error Commented Jun 13, 2019 at 2:02
  • @LutfiCreativesys Please add the code to the question as a progress update. Note: your last code is overwriting the same range over an over, by the other hand using setValues to write one row at a time is very slow. Commented Jun 13, 2019 at 2:19
  • I've updated the script, sir. Commented Jun 13, 2019 at 2:26
  • @LutfiCreativesys Thanks for letting me know. By the way that isn't the proper way of adding a progress update as it "invalidates" the previous answer as you removed appendRow. The proper way is to add the new code at the end because the edit intention isn't to make the question clearer, it's to provide a progress update. Commented Jun 13, 2019 at 2:33
  • 1
    Solved. Thanks @Ruben Commented Jun 13, 2019 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.