Create list of all sheet names in Google Apps Scripts

后端 未结 2 1029
陌清茗
陌清茗 2021-01-20 04:37

My goal

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

相关标签:
2条回答
  • 2021-01-20 04:53

    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()])
      }
    }
    
    0 讨论(0)
  • 2021-01-20 05:09

    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);
    }
    
    0 讨论(0)
提交回复
热议问题