I
I
ilya u2019-01-31 09:08:08
Google Apps Script
ilya u, 2019-01-31 09:08:08

Google Apps Script for Google Sheets: how to rename all sheets in a table with a script?

Greetings!
There are two Google Sheets:

  • Table 1 with initial data. It has n-sheets.
  • Table 2 with information for the user, which is taken from Table 1 using =importrange().
    There are also several sheets in Table 2, the name of which corresponds to the value in the cell.

The sheets in Table 2 should be automatically renamed when the cell changes. The written script + trigger (installable) works for the active or only the first sheet, since the getActiveSheet and renameActiveSheet classes are used:
function NewSheetName() {
 var myValue = SpreadsheetApp.getActiveSheet( ).getRange("J2").getValue();
 SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(myValue);
}

How it works : after the trigger fires, only the first or open sheet is renamed.
As needed : after the trigger fires, all sheets in Table 2 are renamed without additional participation, even without opening the tables.
ps In the manual for scripts, I did not find a class that would work with any sheet, and not just with the active one. How to rename a sheet by ID did not master.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2019-01-31
@DasIstGlitch

You just need to get the sheets of the Table, and rename them as needed.
Decision

SpreadsheetApp.openById('blah-blah')
  .getSheets()
  .forEach(function(sheet) {
    var name = sheet.getRange('J2').getValue();
    if (name)
      try {
        sheet.setName(name);
      } catch (error) {
        console.error('CATCHED', error);
      }
  });

How they do it
The main idea is to iterate through all the elements of the array, sort out the excess, and perform an action with the selected elements. The function userActionRenameSheetsdemonstrates this.
/* exported userActionRenameSheets */

/**
 * Действие пользователя или триггера. Внешний вызов без параметров
 */
function userActionRenameSheets() {
  var spreadsheet = SpreadsheetApp.openById('blah-blah');

  /** @type {filterSheets} */
  var filterSheets = function(sheet) {
    return true;
  };

  /** @type {renameRule} */
  var renameRule = function(sheet) {
    var name = sheet.getRange('J2').getValue();
    if (name)
      try {
        sheet.setName(name);
      } catch (error) {
        console.error('CATCHED', error);
      }
    return sheet;
  };

  var sheets = renameSheetsByCellValue_(spreadsheet, filterSheets, renameRule);
  // Делать что-нибудь дальше
}

/**
 * Переименовывает листы в Таблице согласно заданным правилам
 *
 * @param {GoogleAppsScript.Spreadsheet.Spreadsheet} spreadsheet Таблица,
 *         в которой производим переименование
 * @param {filterSheets} Фильтр листов на всякий случай, вдруг что-то надо да пропустить
 * @param {renameRule} Правило переименования, может возвращать что угодно
 * @param {any[]} Массив отфильрованных результатов функции renameRule
 */
function renameSheetsByCellValue_(spreadsheet, filterSheets, renameRule) {
  var res;
  var sheets = spreadsheet.getSheets();
  if (filterSheets) res = sheets.filter(filterSheets) || sheets;
  if (renameRule) res = res.map(renameRule);
  return res;
}

/**
 * Фильтр листов
 * @callback filterSheets
 * @param {GoogleAppsScript.Spreadsheet.Sheet} sheet Текущий лист
 * @param {number} index Текущий индекс массива
 * @param {GoogleAppsScript.Spreadsheet.Sheet[]} sheets Текущий массив
 * @returns {boolean}
 */

/**
 * Правило переименования
 * @callback renameRule
 * @param {GoogleAppsScript.Spreadsheet.Sheet} sheet Текущий лист
 * @param {number} index Текущий индекс массива
 * @param {GoogleAppsScript.Spreadsheet.Sheet[]} sheets Текущий массив
 * @returns {any}
 */

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question