I have two spreadsheets, SpreadSheetA and SpreadSheetB.
I am trying to get a list of the names of all the sheets in SpreadSheetA and add it to the
Try the below...
function getSheetNamesAndAddToOtherSheet() {
var spreadSheetAURL = "https://docs.google.com/spreadsheets/d/UNIQUE-ID-HERE/edit";
var spreadSheetsInA = SpreadsheetApp.openByUrl(spreadSheetAURL).getSheets();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
for (var i = 0; i < spreadSheetsInA.length; i++) {
sheet.appendRow([spreadSheetsInA[i].getName()])
}
}
The error message hints at what's wrong: the setValues
method expects "Object[][]" that is a double array of things. In Google Sheets, all ranges of data are represented as double arrays, such as [[1, 2], [3, 4]]
. If there is one row, it's still a double array: [[1, 2]]
. If it's one column: [[1], [3]]
.
So you need this extra array dimension, essentially wrapping every sheet name in square brackets. This is done below, where I also used map method to process the array of sheets: this is cleaner and likely more efficient than using push
in a for
loop.
function getSheetNamesAndAddToOtherSheet() {
var spreadSheetAURL = "https://docs.google.com/spreadsheets/d/UNIQUE-ID-HERE/edit";
var sheetNameArray = [];
var spreadSheetsInA = SpreadsheetApp.openByUrl(spreadSheetAURL).getSheets();
sheetNameArray = spreadSheetsInA.map(function(sheet) {
return [sheet.getName()];
});
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = sheet.getRange(1, 1, sheetNameArray.length, 1);
range.setValues(sheetNameArray);
}