Руководство google apps script

30 декабря 2020, автор: Елена Позднякова

Здравствуйте, уважаемые читатели моего блога!
Данная статья-справочник подготовлена для тех, кто хочет автоматизировать Гугл Таблицы с помощью языка программирования Google Apps Script.
Это можно сделать даже с нуля и без начальных навыков программирования, но, единственная проблема в том, что не так-то просто разобраться в официальной документации от Гугла: во-первых, она на английском, во-вторых, очень объемная.
Здесь вы найдете четко структурированный набор самых нужных функций, которые позволят вам свободно ориентироваться в автоматизации Google Таблиц.
Скачайте схему, смотрите видео, если есть вопросы — задавайте в комментариях!

Google Apps Script основные команды для Гугл Таблиц

Имена: как получить доступ или обратиться к таблице, листу, диапазону, ячейке

Таблица как электронный файл (Spreadsheet)

var ss = SpreadsheetApp.openByUrl ( 'https://docs.google.com/spreadsheets/d/abc1234567/edit');

Logger.log ( ss.getName ( ) );

SpreadsheetApp.openById ( id ) — доступ к электронной таблице по ID.

Как получить ID таблицы из URL-адреса:
https://docs.google.com/spreadsheets/d/1bwOBqlm4RJgLLlftChrOTcZgDlZrvjA9fddybkgrto8/edit#gid=0
https://docs.google.com/spreadsheets/d/spreadsheetId/edit#gid=0

var ss = SpreadsheetApp.openById ( "1bwOBqlm4RJgLLlftChrOTcZgDlZrvjA9fddybkgrto8" );

Logger.log (ss.getName ( ) );

Справочно: доступ по имени к таблице не возможен, так как имя таблицы не проверяется на уникальность.

Доступ к родительской таблице из контейнерного скрипта:

//например, получить URL адрес текущей таблицы

SpreadsheetApp.getActive ( ).getUrl ( );
SpreadsheetApp.getActiveSpreadsheet ( ).getUrl ( );

Открыть таблицу, записанную в переменную

Лист (Sheet)

var sheet = SpreadsheetApp.getActiveSpreadsheet ( ) .getSheetByName ( "Лист2" )

Доступ к активному листу для контейнерного скрипта:

getActiveSheet ( ) — доступ к активному листу в электронной таблице.
Активный лист в электронной таблице — это лист, который отображается в пользовательском интерфейсе электронной таблицы.

var sheet = SpreadsheetApp.getActiveSpreadsheet ( ). getActiveSheet ( ); 

//напрямую без указания таблицы тоже можно:

var sheet = SpreadsheetApp.getActiveSheet ( ); 

sheet.getName ( ) — возвращает имя листа =sheet.getSheetName()
sheet.getSheetId ( ) — возвращает ID листа
range.getSheet ( ) — возвращает лист (как объект), к которому принадлежит диапазон

Получить все листы таблицы в виде списка:
ss.getSheets ( ) — получить все листы таблицы в виде списка.
Возможен доступ по индексам. Индексация начинается с 0.

var sheets = SpreadsheetApp.getActiveSpreadsheet ( ) .getSheets ( ) ;

 Logger.log (sheets [0].getName ( ) ); //Лист1

sheet.getIndex ( ) — получает позицию листа в родительской электронной таблице. Начинается с 1.

sheet.getFormUrl ( ) — возвращает URL-адрес формы, которая отправляет ответы в этот лист или null.

Диапазон (Range)

Получить диапазон по номеру строки и столбца:

getRange(row, column, numRows, numColumns) — возвращает диапазон с верхней левой ячейкой в заданных координатах с заданным количеством строк и столбцов.

Пример.
Вывести в журнал все значения из приведенного диапазона:

function showRange () {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var range = sheet.getRange(1, 2, 3, 2);
  var values = range.getValues();
  
  // Напечатать в журнал значения из диапазона с помощью цикла
  for (var row in values) {
    for (var col in values[row]) {
      Logger.log(values[row][col]);
    }
  }
}

Получить диапазон по нотации А1:

Один из вариантов обозначения диапазонов — Нотация А1.
Это строка типа Sheet1!A1:B2.

getRange ( a1Notation ) — получить диапазон по обозначению с помощью нотации А1. Нотация А1 представляет из себя строку и должна быть заключена в кавычки: » » (двойные), ‘ ‘ (одинарные) или ` ` (обратные).

Например:

var range = sheet.getRange('B1:C3').getValues ( );

С помощью обратных кавычек « в текст нотации можно встраивать выражения и переменные:

var row = 3;
var cell = sheet.getRange( `D${row}` ).getValue ( );

Синтаксис для встраивания ${переменная}.
В пределах обратных кавычек не должно быть лишних пробелов, иначе нотация не будет прочитана.

Получить доступ к активному диапазону из контейнерного скрипта:

getActiveRange ( ) — возвращает выбранный диапазон на активном листе или null, если активного диапазона нет. Метод класса SpreadsheetApp.

Примечание: в пользовательской функции диапазон относится к ячейке, которая пересчитывается.

var color = SpreadsheetApp.getActiveRange().getBackgroundColor();

Получить доступ к активному диапазону из независимого скрипта:

getActiveRange ( ) — возвращает выбранный диапазон на активном листе или null, если активного диапазона нет. Метод классов: Spreadsheet, Sheet.

SpreadsheetApp.openById('16tBD3fhiKUFI1mqEyorn6ZqXm0OU3frjLcN8veNiZPg').getActiveRange ( );

getRange (row, column, numRows) — возвращает диапазон с верхней левой ячейкой с заданными координатами и с заданным количеством строк.

Примечание: только один столбец.Пример.
Получить данные столбца, начиная с ячейки B2 до последней заполненной строчки в таблице.

function showColumn (){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[1];

  var range = sheet.getRange(2, 2, 5);
  var values = range.getValues();
  
    for (var row in values) {
    for (var col in values[row]) {
      Logger.log(values[row][col]);
    }
  }
}

Получить столбец по нотации А1:

var range = sheet.getRange('B:B').getValues ( );

function showRow (){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[1];
  
  var range = sheet.getRange(4, 1, 1,3);
  var values = range.getValues();
  
   for (var row in values) {
    for (var col in values[row]) {
      Logger.log(values[row][col]);
    }
  }
}

Получить ряд по нотации А1:

var range = sheet.getRange('4:4').getValues ( );

Ячейка (Cell)

Получить ячейку по номеру строки и столбца:

//из таблицы контейнерного скрипта получить лист с индексом 1 (это второй лист)

var sheet = SpreadsheetApp.getActive().getSheets()[1];

//из ячейки по адресу: РЯД 3 СТОЛБЕЦ 4 получить значение

var cell = sheet.getRange (3, 4) .getValue ( ) ;

Получить ячейку по нотации А1:

getRange ( a1Notation ) — получить ячейку по обозначению с помощью нотации А1. Нотация А1 представляет из себя строку и должна быть заключена в кавычки: » » (двойные), ‘ ‘ (одинарные) или ` ` (обратные).

var cell = sheet.getRange( 'D3' ).getValue ( );

С помощью обратных кавычек « в текст нотации можно встраивать выражения и переменные:

var row = 3;
var cell = sheet.getRange( `D${row}` ).getValue ( );

Синтаксис для встраивания ${переменная}.
В пределах обратных кавычек не должно быть лишних пробелов, иначе нотация не будет прочитана.

Получить доступ к активной ячейке из контейнерного скрипта:

getCurrentCell ( ) — возвращает текущую ячейку на активном листе или null, если текущая ячейка отсутствует.

var number   = SpreadsheetApp.getCurrentCell ( ).getValue ( );

Получить доступ к активной ячейке из независимого скрипта:

getActiveCell ( ) — возвращает активную ячейку на листе.

Примечание: в документации Гугл указано, что предпочтительно использовать getCurrentCell ( )

SpreadsheetApp.openById('16tBD3fhiKUFI1mqEyorn6ZqXm0OU3frjLcN8veNiZPg').getActiveCell().getValue();

Основные команды

Структура команд:

сначала навигация — а затем команда

Класс SpreadsheetApp

главный класс для управление Гугл Таблицами

Все команды начинаются с:

SpreadsheetApp.

Класс Spreadsheet

электронная таблица как документ

openByUrl (url)
openById (id)
getActive ( )
getActiveSpreadsheet ( )

Класс Sheet

лист

getSheetByName (name)
getActiveSheet ( )

Класс Range

диапазон или ячейка

getRange(row, column, numRows, numColumns)
getRange (row, column, numRows)
getRange ( row, column )
getRange ( a1Notation )
getActiveRange ( )
getCurrentCell ( )
getActiveCell ( )

Обычно обращение к классам SpreadsheetApp и Spreadsheet записывают в переменную ss, обращение к классу Sheet в переменную sheet, обращение к классу Range в переменную range.

//Текущая Гугл Таблица записана в переменную:
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  
  //Лист с именем "Лист1" записан в переменную:
  var sheet = ss.getSheetByName("Лист1"); 
  
  //Диапазон A1:B4 записан в переменную:
  var range = sheet.getRange('A1:B4');

Для контейнерного скрипта допустимо прямое обращение к активному листу или активному диапазону (минуя промежуточные классы), так как скрипт создан из родительской таблицы:

SpreadsheetApp.getActiveSheet ( );

//или

SpreadsheetApp.getActiveRange ( );
SpreadsheetApp.getCurrentCell ( );

//для независимого скрипта требуется обязательное обращение к таблице по ID или URL

SpreadsheetApp.openByUrl ( 'URL' ).getActiveCell ( ); 

//или

SpreadsheetApp.openById ( 'ID' ).getSheetByName ( 'name').getRange ( ); 

Основные команды класса SpreadsheetApp

Вставить строки
sheet.insertRowBefore ( beforePosition )
sheet.insertRowAfter ( afterPosition )
sheet.insertRows ( rowIndex )
sheet.insertRows ( rowIndex, numRows )
sheet.insertRowsBefore ( beforePosition, howMany )
sheet.insertRowsAfter ( afterPosition, howMany )

Вставить столбцы
sheet.insertColumnBefore ( beforePosition )
sheet.insertColumnAfter ( afterPosition )
sheet.insertColumns ( columnIndex )
sheet.insertColumns ( columnIndex,numColumns )
sheet.insertColumnsBefore ( beforePosition, howMany )
sheet.insertColumnsAfter ( afterPosition, howMany )

Самые частые команды:

getValue ( ) — setValue ( )
getValues ( ) — setValues ( )

Еще важные команды:

range.getNote — range.setNote
range.getNotes — range.setNotesactivate ( )активировать, команда эквивалентна щелчку мышью
(применима к листу, диапазону, ячейке)

Ссылки на официальную документацию по методам классов SpreadsheetApp, Spreadsheet, Sheet, Range

официальная документация по на английском

официальная документация по на английском

официальная документация по на английском

официальная документация по на английском

Функции других служб для Гугл Таблиц: почта, календари, переводчик и т.д.

Отправить письмо из Гугл Таблицы

MailApp.sendEmail(recipient, subject, body)

function myMail() {
  MailApp.sendEmail("test@test.ru", "лови письмо из гугл таблицы",
  "еее! Всё получилось!!!")
}

Видеоинструкция по функции sendEmail:

Отправить событие из Гугл Таблицы в публичный календарь

CalendarApp.getCalendarById("ID").createEvent(title, startTime, endTime)

function CalendarEvent(){
  var ss = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = ss.getSheetByName('Лист2'),
   
      title = sheet.getRange('A2').getValue(),
      startTime = sheet.getRange('B2').getValue(),
      endTime = sheet.getRange('C2').getValue();
  CalendarApp.getCalendarById("ID").createEvent(title, startTime, endTime);
}  

Видеоинструкция по функции createEvent:

Поисковые запросы в Google Apps Script

sheet.createTextFinder(findText).findNext()

//Создаем поисковый запрос со значением текущего менеджера
  var textFinder = sheet.createTextFinder(currentManager);
  
  //Запускаем поисковый запрос с помощью встроенной функции findNext() и полученное значение записываем в переменную
  //Функцию можно запускать без условий, так как поисковый запрос точно не пустой
  var firstOccurrence = textFinder.findNext();

Видеоинструкция по поисковым запросам в Google Apps Script:

Переводчик в Google Apps Script

LanguageApp.translate(text, sourceLanguage, targetLanguage) 

function translate (){
  var arabic = LanguageApp.translate('Привет', 'ru', 'ar');
  Logger.log(arabic);
} 

// مرحبا

Сообщение alert для Гугл Таблицы

alert(prompt) — функция alert вызывает окно с сообщением, которое блокирует интерфейс таблицы до тех пор, пока пользователь не нажмет ОК.

Для того, чтобы вызвать данную функцию из Гугл Таблицы, требуется дополнительно обратиться к интерфейсу таблицы с помощью встроенной функции от Гугл: SpreadsheetApp.getUi().
getUi() — функция обращается к пользовательскому интерфейсу Гугл Таблицы.

Вот так выглядит скрипт:

function alertSpreadsheet () {
 SpreadsheetApp.getUi().alert("Привет! Это сообщение выведено с помощью функции alert")
 }

Видеоинструкция по данному скрипту:

Получить email пользователя, запустившего скрипт

getEmail() — получает email пользователя текущей сессии.

function CheckMyEmail() {
  var email = Session.getActiveUser().getEmail()
  Logger.log('Твой email: ' + email)
 }

Получить текущую дату и время

Описание, как работать с датой и временем в рекламных скриптах Гугл.

function todayNow () {
  var today = Date ();
  Logger.log(today)
  }

//Tue Dec 29 2020 17:53:43 GMT+0300 (Москва, стандартное время)

function todayNow2() {
  var today = new Date().toLocaleString('ru');
  Logger.log(today)
  }

//29.12.2020, 18:06:08

Математические операции с датами. В приведенном ниже фрагменте скрипта переменная yesterday выражает время ровно 24 часа назад от текущего момента.

function yesterday (){
  var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
  var now = new Date();
  var yesterday = new Date(now.getTime() - MILLIS_PER_DAY);
  Logger.log(yesterday)
}

//Mon Dec 28 18:02:23 GMT+03:00 2020

Триггеры, которые запускают функции

Простые триггеры

Мы разберем два простых триггера: onEdit (срабатывает при любом изменении в Гугл Таблице) и onOpen (срабатывает при открытии).
Начнем с функции onEdit, а функцию onOpen рассмотрим в следующем разделе для целей создания пользовательского меню.

OnEdit (e) — функция onEdit является простым триггером. Выполняется при редактировании ячейки.

Синтаксис:

function onEdit(e) {
команда
}

onEdit — это зарезервированное имя функции, для триггера нужно использовать только его;
e — это не обязательный аргумент, который передает информацию об объекте события.

Перечень объектов, которые содержатся в e, можно посмотреть здесь.
Например:

  • range — ячейка или диапазон ячеек, который был изменен (обратиться к диапазону: e.range);
  • value — новое значение для ячейки (доступно только для редактирования одиночной ячейки, обратиться к значению: e.value);
  • sourse — Гугл Таблица (обратиться: e.sourse).

Пример1.
Триггер добавляет примечание к любой ячейке, которая была изменена.

function onEdit(e) {
  
  var range = e.range;
  
   range.setNote('Последнее изменение: ' + new Date().toLocaleString('ru'))
  }

Пример2.
Триггер добавляет примечание, если была изменена ячейка из столбца 2.

function onEdit(e) {
  
  var range = e.range;
  
  if (range.getColumn() == '2')
    
  {range.setNote('Последнее изменение: ' + new Date().toLocaleString('ru'))
  }
}

Пример3.
Триггер записывает время последнего изменения в ячейку справа от измененной ячейки.

function onEdit(e) {
  
// Это контейнерный скрипт:
// e = SpreadsheetApp.getActiveRange()
  
  var range = e.range,
      row =   range.getRow(),
      column =   range.getColumn();
  
  
  range.offset(0, 1).setValue(new Date().toLocaleString('ru'))
  
}

Пользовательское меню

С помощью Google Apps Script можно создать пользовательское меню для Гугл Таблицы. Создание меню доступно только из Контейнерного скрипта.
Меню Гугл Таблицы будет видеть только тот, кто имеет право редактирования (пользователи с доступом на просмотр меню не видят).

Вот так выглядит простейшее пользовательское меню:

function onOpen() {
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('МОЁ МЕНЮ')
    .addItem('Запустить функцию 1', 'myFunction1')
    .addSeparator()
    .addItem( 'Запустить функцию 2', 'myFunction2')
    .addToUi();
}

А здесь пользовательское меню для Гугл Документа, которое включает подменю:

function onOpen() {
  var ui = DocumentApp.getUi();
  // или SpreadsheetApp или FormApp.
  ui.createMenu('ПОЛЬЗОВАТЕЛЬСКОЕ МЕНЮ')
  .addItem('Пункт меню1', 'function1')
  .addItem('Пункт меню2', 'function2')
  .addSeparator()
  .addSubMenu(ui.createMenu('Подменю')
              .addItem('Пункт подменю 1', 'function3')
              .addItem('Пункт подменю 2', 'function4'))
  .addToUi();
}

Функция onOpen является простым триггером. Выполняется при открытии документа.
Авторизация пользователя для запуска этой функции не требуется, поэтому возможности её ограничены лишь несколькими действиями.
В частности, для onOpen доступно создание пользовательского меню для Гугл Таблицы.

addItem ( caption, functionName ) — функция добавляет элемент меню
caption — название элемента меню
finctionName — функция, которую запускает элемент меню

Кнопки

Функции можно запускать из редактора скриптов с помощью кнопки «Выполнить»:

Кроме этого, команду на выполнение функции можно перенести в Гугл Таблицу, чтобы функция запускалась из таблицы (не заходя в редактор скриптов).
Для этого в Гугл Таблице нужно создать кнопку и назначить на неё скрипт.
Кнопкой может быть любое изображение, вставленное поверх ячеек, или кнопкой может быть рисунок.

ВставкаИзображение Изображение поверх ячеек
или
Вставка Рисунок (нарисовать любую фигуру)

дальше одинаково:
• • • → Назначить скриптВписать название функции без ( )

Управление триггерами вручную

  1. Откройте проект Apps Script.
  2. Слева нажмите Триггеры.
  3. В правом нижнем углу нажмите Добавить триггер .
  4. Выберите и настройте тип триггера, который вы хотите создать.
  5. Щелкните Сохранить .

Программное управление триггерами

function createTimeDrivenTrigger() {
  
  // Триггер сработает каждое утро в 09:00.
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .onWeekDay(ScriptApp.WeekDay.MONDAY)
      .atHour(9)
      .create();
}

Пользовательские функции

Видео инструкция:

Пишем свою пользовательскую функцию для Гугл Таблиц с помощью Google Apps Script

Пример пользовательской функции «Перевод километров в морские мили»:

//Пользовательская функция для встроенного скрипта "Перевод километров в морские мили"
//Комментарий ниже является аннотацией для создания подсказок

/**
* Функция переводит километры в морские мили.
*
* @param {number} kilometers километры.
* @return {number} nauticalMiles морские мили.
* @customfunction
*/

function kilometersToNauticalMiles ( kilometers ) {
  var nauticalMiles = kilometers/1.8522;
  return nauticalMiles
}

Полезные фишки
и ссылки на дополнительные материалы по JavaScript

Макросы — основа скрипта для умных лентяев

Запишите макрос, и скрипт сам запомнит ваши действия и сделает из них сценарий:
Инструменты → Макросы → Запись макроса

Особенно хороши макросы для подготовки сценариев с форматированием данных. Цвет, размер текста, форматы — все это удобнее ПОКАЗАТЬ, чем искать соответствующие команды.
Настройку проверки данных (выбор значений из списка, флажок) тоже удобнее настраивать через макрос, чем искать в командах.

Записанный сценарий ждет вас в меню:
Инструменты → Редактор скриптов

Google Apps Script? Сейчас объясню!
[подборка видео от Автоматизации без обязательств]

Google Apps Script на русском

JavaScript — основа Google Apps Script

JavaScript на одном листе

Учебник по JavaScript

Полный курс по JavaScript за 6 часов
от Владилена Минина

Google Apps Script allows you to programmatically create and modify Google Docs,
as well as customize the user interface with new menus, dialog boxes, and
sidebars.

The basics

Apps Script can interact with Google Docs in two broad ways: any script can
create or modify a document if the script’s user has appropriate permissions for
the document, and a script can also be
bound to a document, which gives
the script special abilities to alter the user interface or respond when the
document is opened. To create a container-bound script from within Google Docs,
click Extensions > Apps Script.

In either case, it’s simple to interact with a Google Doc through Apps Script’s
Document Service, as the following example
demonstrates.

function createDoc() {
  var doc = DocumentApp.create('Sample Document');
  var body = doc.getBody();
  var rowsData = [['Plants', 'Animals'], ['Ficus', 'Goat'], ['Basil', 'Cat'], ['Moss', 'Frog']];
  body.insertParagraph(0, doc.getName())
      .setHeading(DocumentApp.ParagraphHeading.HEADING1);
  table = body.appendTable(rowsData);
  table.getRow(0).editAsText().setBold(true);
}

The script above creates a new document in the user’s Google Drive, then inserts
a paragraph that contains the same text as the document’s name, styles that
paragraph as a heading, and appends a table based on the values in a
two-dimensional array. The script could just as easily make these changes to an
existing document by replacing the call to
DocumentApp.create()
with DocumentApp.openById()
or openByUrl().
For scripts created inside a document (container-bound), use
DocumentApp.getActiveDocument().

Structure of a document

From Apps Script’s perspective, a Google Doc is structured much like an HTML
document—that is, a Google Doc is composed of elements (like a
Paragraph or
Table) that often contain other
elements. Most scripts that modify a Google Doc begin with a call to
getBody(), because the
Body is a master element that
contains all other elements except for the
HeaderSection,
FooterSection, and any
Footnotes.

However, there are rules about which types of elements can contain other types.
Furthermore, the Document Service in Apps Script can only insert certain types
of elements. The tree below shows which elements can be contained by a certain
type of element.

Elements shown in bold can be inserted; non-bold elements can only be
manipulated in place.

  • Document
    • Body
      • ListItem
        • Equation
          • EquationFunction
            • EquationFunction…
            • EquationFunctionArgumentSeparator
            • EquationSymbol
            • Text
          • EquationSymbol
          • Text
        • Footnote
        • HorizontalRule
        • InlineDrawing
        • InlineImage
        • PageBreak
        • Text
      • Paragraph
        • Equation
          • EquationFunction
            • EquationFunction…
            • EquationFunctionArgumentSeparator
            • EquationSymbol
            • Text
          • EquationSymbol
          • Text
        • Footnote
        • HorizontalRule
        • InlineDrawing
        • InlineImage
        • PageBreak
        • Text
      • Table
        • TableRow
          • TableCell
            • Paragraph
            • ListItem
            • Table
      • TableOfContents
        • Paragraph…
        • ListItem…
        • Table…
    • HeaderSection
      • ListItem
        • HorizontalRule
        • InlineDrawing
        • InlineImage
        • Text
        • UnsupportedElement (page number, etc.)
      • Paragraph
        • HorizontalRule
        • InlineDrawing
        • InlineImage
        • Text
        • UnsupportedElement (page number, etc.)
      • Table
        • TableRow
          • TableCell
            • Paragraph
            • ListItem
            • Table
    • FooterSection
      • ListItem
        • HorizontalRule
        • InlineDrawing
        • InlineImage
        • Text
        • UnsupportedElement (page number, etc.)
      • Paragraph
        • HorizontalRule
        • InlineDrawing
        • InlineImage
        • Text
        • UnsupportedElement (page number, etc.)
      • Table
        • TableRow
          • TableCell
            • Paragraph
            • ListItem
            • Table
    • FootnoteSection
      • ListItem
        • HorizontalRule
        • Text
      • Paragraph
        • HorizontalRule
        • Text

Replacing text

Apps Script is often used to replace text in Google Docs. Let’s say you have a
spreadsheet full of client information and you want to generate a personalized
Google Docs for each client. (This type of operation is often called a mail
merge.)

There are many ways to replace text, but the simplest is the
replaceText() method shown in the example below. replaceText supports most
of JavaScript’s regular expression features. The first function below
adds several lines of placeholder text to a Google Docs; in the real world, you
would be more likely to type the placeholders into the document yourself. The
second function replaces the placeholders with properties defined in the
client object.

Note that both of these functions use the
getActiveDocument()
method, which only applies to scripts created inside a Google Doc; in a
stand-alone script, use
DocumentApp.create(),
openById(),
or openByUrl()
instead.

Add some placeholders

function createPlaceholders() {
  var body = DocumentApp.getActiveDocument().getBody();
  body.appendParagraph('{name}');
  body.appendParagraph('{address}');
  body.appendParagraph('{city} {state} {zip}');
}

Replace the placeholders

function searchAndReplace() {
  var body = DocumentApp.getActiveDocument()
      .getBody();
  var client = {
    name: 'Joe Script-Guru',
    address: '100 Script Rd',
    city: 'Scriptville',
    state: 'GA',
    zip: 94043
  };

  body.replaceText('{name}', client.name);
  body.replaceText('{address}', client.address);
  body.replaceText('{city}', client.city);
  body.replaceText('{state}', client.state);
  body.replaceText('{zip}', client.zip);
}

Custom menus and user interfaces

You can customize Google Docs by adding menus, dialog boxes, and
sidebars. Keep in mind, however, that a script can only interact with the UI for
the current instance of an open document, and only if the script is
bound to the document.

See how to add custom menus and
dialogs to your Google Docs.
To learn more about creating custom interfaces for a dialog or sidebar, see the
guide to HTML Service.
If you’re planning to publish your custom interface as part of an
add-on, follow the
style guide for consistency with the
style and layout of the Google Docs editor.

Add-ons for Google Docs

Add-ons run inside Google Docs and can be installed
from the Google Docs add-on store. If you’ve developed a script for Google Docs
and want to share it with the world, Apps Script lets you
publish your script as an
add-on so other users can install it from the add-on store.

To see how you can create an add-on for Google Docs, see
quickstart for building Docs add-ons.

Triggers

Scripts that are bound to a Google
Doc can use a simple trigger to respond
to the document’s onOpen event, which
occurs whenever a user who has edit access to the document opens it in Google Docs.

To set up the trigger, just write a function called onOpen(). For an example
of this trigger, see Custom menus in Google Workspace.
Although the simple trigger is useful for adding menus, it cannot use any Apps
Script services that require authorization.

Последнее обновление: 13 февраля 2018 г. 19 июня 2020 г.

А вы слыхали про гугл скрипты (Apps Script)? Нет?

Ну, как же так получилось? Ай-яй-яй!

Такая полезная вещь, а о ней в курсе лишь узкий круг специалистов. А зря!

Такая ситуация сложилась в русскоязычном сообществе, в англоязычном же интернет пространстве он довольно популярен (что видно из графиков ниже).

Почему зря?

А потому, что это прекрасный инструмент для малого и среднего бизнеса, который позволяет без лишних затрат оптимизировать документооборот и наладить автоматическую работу жизненно важных процессов предприятия.

Та что там бизнес, каждый оценит по достоинству возможности этого сервиса, ведь способов применения просто бездна!

Стоит немного вникнуть в кухню сервисов гугл, как, прям таки, перехватывает дыхание от открывающихся перспектив!

Но не будем забегать вперед.

Для начала необходимо разобраться что это такое и что с этим делать.

Google Apps script — что это?

G-Apps-Script | Фото - Сервисы Google

Давным давно (с 2009 года) великий гугл выпустил полезную фичу — Google Apps script.

Этот сервис дает возможность автоматизировать работу сервисов гугл. Самый близкий аналог — это офисный пакет Microsoft Office со своими макросами на VBA (Visual Basic for Applications) и его аналоги Libre Office, SoftMaker Office и т.п.

Конечно, не совсем корректно сравнивать сравнвать GAS и VBA.

Вот что об этом говорит один из ведущих специалистов по сервисам google в русскоязычном интернете, Александр Иванов.

Единственное, что их объединяет, это идея расширения возможностей табличного процессора за счет дополнительного программного кода. …

Александр Иванов

Консультант по Google Apps Script

Ознакомится с более подробным сравнением, которое Александр любезно составил специально для нас с вами, можно по этой ссылке.

Конечно, у многих, кто пытался с ходу освоить использование макросов могли остаться не слишком приятные воспоминания, однако не стоит сразу морщиться!

Gooogle Apps script — куда более дружелюбно настроенный к пользователю язык, чем может показаться на первый взгляд.

Фактически это язык сценариев на базе JavaScript (стандарта ECMAScript 5), придуманный специально для того чтобы существенно упростить разработку приложений на основе Google Apps.

Для тех, кто в танке, напоминаю, что Google Apps (кстати, пакет недавно переименовали в G Suit) — это интернет-сервисы разработанные транснациональной корпорацией и с которыми в той или иной степени знаком каждый.

Сервисы гугл

(которые мы будем рассматирвать, писать для них сценарии на gas):

и многие другие, список приложений постоянно растет (тут можно посмотреть весь список продуктов google).

Так вот, основные преимущества работы с гугл скриптами — это выполнение кода не на клиенте (т.е. непосредственно не на вашем рабочем компьютере), а в облаке Google.

Что дарит возможность создания автономных сценариев, для работы которых не требуется вмешательство пользователя (очень крутая фишка!).

Кроме того, для начала работы не требуется ничего устанавливать, Google уже обо всем позаботился.

Есть готовый редактор со всем необходимым функционалом (фото ниже).

К плюсам также можно причислить

  • Достаточно низкий порог входа, т.е. легко обучаемый язык.
  • Возможность взаимодействия и с другими службами Google, такими как AdSense, Google Analytics, AdWords и тп.
  • Возможность создавать полноценные веб-приложения с графическим интерфейсом на HTML.
  • Также возможность делать http-запросы и обрабатывать их результаты (парсинг). Тоесть с помощью класса UrlFetchApp в gas можно извлекать данные с веб-страниц и парсить XML/JSON ответы REST API сервисов.
  • Достаточный функционал для создания простых инструментов, необходимых в работе предприятия, вплоть до полноценной CRM системы.
  • Развитое комьюнити, в смысле, множество готовых решений и людей охочих подсказать и, конечно, документация. Правда все эти прелести в своем большинстве ориентированы на англоязычную публику.
  • и многое другое.

Первый шаг — создание скрипта

Не будем ходить вокруг, да около… Напишем свой первый скрипт прямо сейчас.

Создание скрипта через панель инструментов Script Script

Для начала зайдите в свой аккаунт Google (напомним, что для доступа ко всем сервисам требуется только один аккаунт, который заводится вместе с гугловской почтой), а затем переходим по следующей ссылке script.google.com и попадаем на вот такую страницу (панель инструментов Script Script):

G-Apps-Script | Фото - Панель инструментов Google Script

В левом боковом меню, кликните на кнопку + Создать скрипт.

G-Apps-Script | Фото - Создать сценарий

Перед вами окно редактора гугл скриптов:

G-Apps-Script | Фото - Окно редактора Google Сценариев

К слову, это не единственный способ его запуска.

Можно пойти и другим путем.

Создание скрипта через Google Диск

Сперва, заходим на Google Диск.

G-Apps-Script | Фото - Google Диск

Клацаем на кнопочку Создать, выпадет список с вариантами, тут выбираем Еще и жмем на Подключить другие приложения.

G-Apps-Script | Фото - Google Диск, подключить другие приложения

В окошке подключений, в поиске, вводим Google Apps script клацаем Подключить и… вуаля!

G-Apps-Script | Фото - Google Диск, подключить приложение Google Apps script

В окне Приложение Google Apps Script добавлено на Google Диск., устанавливаем птицу напротив Выбрать Google Apps Script приложеним по умочанию для файлов, которые открываются с его помощью. и жмем на ок

G-Apps-Script | Фото - Google Диск, подключить приложение Google Apps script

Теперь в списке ваших возможностей появился новый сервис и мы можем приступать непосредственно к коду.

G-Apps-Script | Фото - Google Диск, создание файла для сценария

Создание скрипта через файл-контейнер

Кроме того существует еще один способ создать файл для сценария.

Это создание файла-сценария внутри файла-контейнера (например внутри таблицы, документа, слайда или формы, условно внутри).

Но этот способ мы разберем в следующих статьях.

Первый скрипт

Создаем свой первый скрипт.

Можно, конечно, сходить вот по этой ссылочке тыц и внимательно почитать что пишут знающие люди, или…

Не ходить, а просто отдаться в руки автора (т.е. в мои)) ) и читать дальше…

Тем, кто никогда не пробовал свои силы в программировании, наверняка, “лаконичное” окно редактора покажется совершенно загадочным и возможно некоторым даже захочется сбежать с криками: “Меня обманули, говорили, что это просто!!!

Не спешите смазывать лыжи! Это действительно просто, если, конечно, знать что делать.

G-Apps-Script | Фото - Не спешите смазывать лыжи!

Так уж повелось, еще на заре цифровых технологий, первым тестовым сообщением, которое выводит свеженаписанная программа это: “Привет мир!”.

Предлагаю чуть, отступить от канонов и вывести куда-нибудь сразу перевод знаменитого приветствия…ну, скажем, на суахили!

Для начала меняем название функции с myFunction на firstTest.

Далее пишем вот такую аБрА-КадабРу:

function firstTest () {
  return Logger.log( LanguageApp.translate("Hello World!", "en", "sw") );
}

Давайте распишем тот же пример более подробно и разберем каждую строку

function firstTest () {
    var text = "Hello World!",
        text_language = "en",
        language_of_translation = "sw";
	
    text = LanguageApp.translate(
        text,
        text_language,
        language_of_translation
    );
	
    Logger.log( text );

    return;
}

Строка 1. Директива function создает новую функцию, далее указываем ее название firstTest.

Затем в круглых скобках () указываем параметры которые хотим передать в функцию (в нашем случае мы ничего не указываем, так как ничего не передаем).

А в фигурных скобках {} указывается код который выполняется когда эта функция будт вызвана.

function firstTest () {
    // Тут код функции
}

Если поставить два слеша //, то код после них и до конца строки выполнятся не будет.

Это называется комментарий.

К слову, комментарий еще можно указать так /* */, любой текст заключенный внутри будет считатся комментарием, независимо от начала и/или конца строк(и).

Строки 2-4. Объявляем переменные с помощью директивы var.

  • Переменная text со значением “Hello World!” — это текст, который требуется перевести,
  • text_language со значением “en” — код языка на котором написан текст, если оставить его пустым (вот так “”), язык будет определяться автоматически,
  • И language_of_translation со значением “sw” — код языка на который будет переведен текст.

(коды языков можно подсмотреть здесь)

var text = "Hello World!",
    text_language = "en",
    language_of_translation = "sw";

Строки 6-10. Обращаемся к объекту LanguageApp, а точнее к методу этого объекта translate, который принимает три параметра (их мы уже описали выше в строках 2-4).

Если некоторые термины вам непонятны и/или у вас нет базовых знаний JavaScript или другого языка, не расстраивайтесь!

В конце статьи я дам ссылку на простой учебник по JS.

Результат

Результатом работы этого метода будет — переведенный текст, который, в нашем случае, записывается в переменную text (то есть перезаписываем старое значение на новое).

text = LanguageApp.translate(
    text,
    text_language,
    language_of_translation
);

Строка 12. Logger.log( text ) — это вывод нашего текста в журнал, где потом мы и будем его смотреть.

Logger.log( text );

К слову, данный способ ( Logger.log(); ) в будущем не раз пригодится для отладки ваших сценариев, т.е. поиска и устранения ошибок, закравшихся в ваш сценарий.

Строка 14. Необязательная директива return — возвращает данные, указанные поле нее (мы ничего не указали, а это значит что по умолчанию возвратится false, с таким же успехом данную директиву можно было не указывать).

    return;

Продолжим, наша программа написана, теперь сохраним ее нажав на эту кнопку (иконка дискеты)

G-Apps-Script | Фото - Сохранение программы

К вам тут же выскочит окошко.

В нем вводим название проекта в поле Укажите новое название проекта, пусть будет Привет мир!. Затем жмем на кнопку ok

G-Apps-Script | Фото - Окно "Изменение названия проекта

Теперь запустим ее, сначала выбрав нужную функцию а затем нажав на вот тут (иконка треугольник)

G-Apps-Script | Фото - Запуск программы

И наконец, идем во вкладку Вид > Журналы или просто нажимаем Ctrl+Enter (горячии клавиши полезная штука).

И вот результат наших стараний…

G-Apps-Script | Фото - Результат работы скрипта

Синим подчеркнута информация, сообщающая когда была сделана запись,

а красным наше содержимое переменной text.

Да, да — Salamu, Dunia! И есть перевод знаменитого Hello World на суахили.

Задача выполнена!

Овации! Чувствуете гордость? Совершенно заслуженно.

G-Apps-Script | Фото - Овации!

Мы с вами сделали первый шаг к освоению замечательного инструмента.

Согласитесь, без ложной скромности, что это было не так уж и сложно.

Остались вопросы?

Вы всегда можете задать их в комментариях к данному посту.

Да и поэкспериментируйте с кодом, а потом покажите нам его в комментариях.

Итоги

А теперь, коротко, подведем итоги:

  • Установка сервиса GAS простая процедура, которая займет меньше минуты.
  • Запустить редактор скриптов можно по ссылке script.google.com
  • LanguageApp.translate(text, sourceLanguage, targetLanguage); — автоматически переводит текст с исходного языка на целевой язык, он принимает 3 параметра: исходный текст, язык текста, язык перевода.
  • Журнал очень полезен для отладки сценариев.
  • Salamu, Dunia!Hello World на суахили.
  • GAS — не так все сложно, как кажется.

Надеюсь мне удалось донести мысль, что Google Apps Script удивительно полезный инструмент, на изучение которого стоит потратить время.

А дальше больше!

В следующей статье рассмотрим подробнее возможности и функционал редактора.

То бишь, все эти кнопочки, вкладочки и т.п.

Сделав первый шаг к цели, не стоит останавливаться. Как гласит древняя мудрость:

Дорога…

…. возникает….

… под шагами идущего…

Полезные ссылки и источники

  • Панель инструментов Google Script (на английском)
  • Основы JavaScript
  • Чтобы получить мнение или поговорить о проблеме, с которой вы сталкиваетесь, я рекомендую вам размещать сообщения в сообществе на Telegram или на Stack Overflow

Beginner Apps Script💡 Learn moreLearn how to write Apps Script and turbocharge your Google Workspace experience with the new Beginner Apps Script course

What is Google Apps Script?

Google Apps Script is a cloud-based scripting language for extending the functionality of Google Apps and building lightweight cloud-based applications.

It means you write small programs with Apps Script to extend the standard features of Google Workspace Apps. It’s great for filling in the gaps in your workflows.

With Apps Script, you can do cool stuff like automating repeatable tasks, creating documents, emailing people automatically and connecting your Google Sheets to other services you use.

Writing your first Google Script

In this Google Sheets script tutorial, we’re going to write a script that is bound to our Google Sheet. This is called a container-bound script.

(If you’re looking for more advanced examples and tutorials, check out the full list of Apps Script articles on my homepage.)

Hello World in Google Apps Script

Let’s write our first, extremely basic program, the classic “Hello world” program beloved of computer teaching departments the world over.

Begin by creating a new Google Sheet.

Then click the menu: Extensions > Apps Script

This will open a new tab in your browser, which is the Google Apps Script editor window:

Google Apps Script Editor

By default, it’ll open with a single Google Script file (code.gs) and a default code block, myFunction():

function myFunction() {
  
}

In the code window, between the curly braces after the function myFunction() syntax, write the following line of code so you have this in your code window:

function myFunction() {
  Browser.msgBox("Hello World!");
}

Your code window should now look like this:

Hello World Apps Script

Google Apps Script Authorization

Google Scripts have robust security protections to reduce risk from unverified apps, so we go through the authorization workflow when we first authorize our own apps.

When you hit the run button for the first time, you will be prompted to authorize the app to run:

Google Apps Script Authorization

Clicking Review Permissions pops up another window in turn, showing what permissions your app needs to run. In this instance the app wants to view and manage your spreadsheets in Google Drive, so click Allow (otherwise your script won’t be able to interact with your spreadsheet or do anything):

Google Apps Script Access

❗️When your first run your apps script, you may see the “app isn’t verified” screen and warnings about whether you want to continue.

In our case, since we are the creator of the app, we know it’s safe so we do want to continue. Furthermore, the apps script projects in this post are not intended to be published publicly for other users, so we don’t need to submit it to Google for review (although if you want to do that, here’s more information).

Click the “Advanced” button in the bottom left of the review permissions pop-up, and then click the “Go to Starter Script Code (unsafe)” at the bottom of the next screen to continue. Then type in the words “Continue” on the next screen, click Next, and finally review the permissions and click “ALLOW”, as shown in this image (showing a different script in the old editor):

More information can be found in this detailed blog post from Google Developer Expert Martin Hawksey.

Running a function in Apps Script

Once you’ve authorized the Google App script, the function will run (or execute).

If anything goes wrong with your code, this is the stage when you’d see a warning message (instead of the yellow message, you’ll get a red box with an error message in it).

Return to your Google Sheet and you should see the output of your program, a message box popup with the classic “Hello world!” message:

Message Box Google Sheets

Click on Ok to dismiss.

Great job! You’ve now written your first apps script program.

Rename functions in Google Apps Script

We should rename our function to something more meaningful.

At present, it’s called myFunction which is the default, generic name generated by Google. Every time I want to call this function (i.e. run it to do something) I would write myFunction(). This isn’t very descriptive, so let’s rename it to helloWorld(), which gives us some context.

So change your code in line 1 from this:

function myFunction() {
  Browser.msgBox("Hello World!");
}

to this:

function helloWorld() {
  Browser.msgBox("Hello World!");
}

Note, it’s convention in Apps Script to use the CamelCase naming convention, starting with a lowercase letter. Hence, we name our function helloWorld, with a lowercase h at the start of hello and an uppercase W at the start of World.

Adding a custom menu in Google Apps Script

In its current form, our program is pretty useless for many reasons, not least because we can only run it from the script editor window and not from our spreadsheet.

Let’s fix that by adding a custom menu to the menu bar of our spreadsheet so a user can run the script within the spreadsheet without needing to open up the editor window.

This is actually surprisingly easy to do, requiring only a few lines of code. Add the following 6 lines of code into the editor window, above the helloWorld() function we created above, as shown here:

function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('My Custom Menu')
      .addItem('Say Hello', 'helloWorld')
      .addToUi();
}

function helloWorld() {
  Browser.msgBox("Hello World!");
}

If you look back at your spreadsheet tab in the browser now, nothing will have changed. You won’t have the custom menu there yet. We need to re-open our spreadsheet (refresh it) or run our onOpen() script first, for the menu to show up.

To run onOpen() from the editor window, first select then run the onOpen function as shown in this image:

Google Apps Script Function Menu

Now, when you return to your spreadsheet you’ll see a new menu on the right side of the Help option, called My Custom Menu. Click on it and it’ll open up to show a choice to run your Hello World program:

Custom menu

Run functions from buttons in Google Sheets

An alternative way to run Google Scripts from your Sheets is to bind the function to a button in your Sheet.

For example, here’s an invoice template Sheet with a RESET button to clear out the contents:

Button with apps script in google sheets

For more information on how to do this, have a look at this post: Add A Google Sheets Button To Run Scripts

Google Apps Script Examples

Macros in Google Sheets

Another great way to get started with Google Scripts is by using Macros. Macros are small programs in your Google Sheets that you record so that you can re-use them (for example applying standard formatting to a table). They use Apps Script under the hood so it’s a great way to get started.

Read more: The Complete Guide to Simple Automation using Google Sheets Macros

Custom function using Google Apps Script

Let’s create a custom function with Apps Script, and also demonstrate the use of the Maps Service. We’ll be creating a small custom function that calculates the driving distance between two points, based on Google Maps Service driving estimates.

The goal is to be able to have two place-names in our spreadsheet, and type the new function in a new cell to get the distance, as follows:

GAS custom function for maps

The solution should be:

GAS custom map function output

Copy the following code into the Apps Script editor window and save. First time, you’ll need to run the script once from the editor window and click “Allow” to ensure the script can interact with your spreadsheet.

function distanceBetweenPoints(start_point, end_point) {
  // get the directions
  const directions = Maps.newDirectionFinder()
     .setOrigin(start_point)
     .setDestination(end_point)
     .setMode(Maps.DirectionFinder.Mode.DRIVING)
     .getDirections();
  
  // get the first route and return the distance
  const route = directions.routes[0];
  const distance = route.legs[0].distance.text;
  return distance;
}

Saving data with Google Apps Script

Let’s take a look at another simple use case for this Google Sheets Apps Script tutorial.

Suppose I want to save copy of some data at periodic intervals, like so:

save data in google sheet

In this script, I’ve created a custom menu to run my main function. The main function, saveData(), copies the top row of my spreadsheet (the live data) and pastes it to the next blank line below my current data range with the new timestamp, thereby “saving” a snapshot in time.

The code for this example is:

// custom menu function
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('Custom Menu')
      .addItem('Save Data','saveData')
      .addToUi();
}

// function to save data
function saveData() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getSheets()[0];
  const url = sheet.getRange('Sheet1!A1').getValue();
  const follower_count = sheet.getRange('Sheet1!B1').getValue();
  const date = sheet.getRange('Sheet1!C1').getValue();
  sheet.appendRow([url,follower_count,date]);
}

See this post: How To Save Data In Google Sheets With Timestamps Using Apps Script, for a step-by-step guide to create and run this script.

Google Apps Script example in Google Docs

Google Apps Script is by no means confined to Sheets only and can be accessed from other Google Workspace tools.

Here’s a quick example in Google Docs, showing a script that inserts a specific symbol wherever your cursor is:

Google Docs Apps Script

We do this using Google App Scripts as follows:

1. Create a new Google Doc

2. Open script editor from the menu: Extensions > Apps Script

3. In the newly opened Script tab, remove all of the boilerplate code (the “myFunction” code block)

4. Copy in the following code:

// code to add the custom menu
function onOpen() {
  const ui = DocumentApp.getUi();
  ui.createMenu('My Custom Menu')
      .addItem('Insert Symbol', 'insertSymbol')
      .addToUi();
}

// code to insert the symbol
function insertSymbol() {  
  // add symbol at the cursor position
  const cursor = DocumentApp.getActiveDocument().getCursor();
  cursor.insertText('§§');
  
}

5. You can change the special character in this line

cursor.insertText('§§');

to whatever you want it to be, e.g.

cursor.insertText('( ͡° ͜ʖ ͡°)');

6. Click Save and give your script project a name (doesn’t affect the running so call it what you want e.g. Insert Symbol)

7. Run the script for the first time by clicking on the menu: Run > onOpen

8. Google will recognize the script is not yet authorized and ask you if you want to continue. Click Continue

9. Since this the first run of the script, Google Docs asks you to authorize the script (I called my script “test” which you can see below):

Docs Apps Script Auth

10. Click Allow

11. Return to your Google Doc now.

12. You’ll have a new menu option, so click on it:

My Custom Menu > Insert Symbol

13. Click on Insert Symbol and you should see the symbol inserted wherever your cursor is.

Google Apps Script Tip: Use the Logger class

Use the Logger class to output text messages to the log files, to help debug code.

The log files are shown automatically after the program has finished running, or by going to the Executions menu in the left sidebar menu options (the fourth symbol, under the clock symbol).

The syntax in its most basic form is Logger.log(something in here). This records the value(s) of variable(s) at different steps of your program.

For example, add this script to a code file your editor window:

function logTimeRightNow() {
  const timestamp = new Date();
  Logger.log(timestamp);
}

Run the script in the editor window and you should see:

Google Apps Script Execution Logs

Real world examples from my own work

I’ve only scratched the surface of what’s possible using G.A.S. to extend the Google Apps experience.

Here are a couple of interesting projects I’ve worked on:

1) A Sheets/web-app consisting of a custom web form that feeds data into a Google Sheet (including uploading images to Drive and showing thumbnails in the spreadsheet), then creates a PDF copy of the data in the spreadsheet and automatically emails it to the users. And with all the data in a master Google Sheet, it’s possible to perform data analysis, build dashboards showing data in real-time and share/collaborate with other users.

2) A dashboard that connects to a Google Analytics account, pulls in social media data, checks the website status and emails a summary screenshot as a PDF at the end of each day.

Marketing dashboard using Google Apps Script

3) A marking template that can send scores/feedback to students via email and Slack, with a single click from within Google Sheets. Read more in this article: Save time with this custom Google Sheets, Slack & Email integration

My own journey into Google Apps Script

My friend Julian, from Measure School, interviewed me in May 2017 about my journey into Apps Script and my thoughts on getting started:

Google Apps Script Resources

For further reading, I’ve created this list of resources for information and inspiration:

Course

Beginner Apps Script💡 Learn moreLearn how to write Apps Script and turbocharge your Google Workspace experience with the new Beginner Apps Script course

Documentation

Official Google Documentation

Google Workspace Developers Blog

Communities

Google Apps Script Group

Stack Overflow GAS questions

Elsewhere On The Internet

A huge big up-to-date list of Apps Script resources hosted on GitHub.

For general Javascript questions, I recommend this JavaScript tutorial page from W3 Schools when you’re starting out.

When you’re more comfortable with Javascript basics, then I recommend the comprehensive JavaScript documentation from Mozilla.

Imagination and patience to learn are the only limits to what you can do and where you can go with GAS. I hope you feel inspired to try extending your Sheets and Docs and automate those boring, repetitive tasks!

Related Articles

Google Sheets has a large number of built-in functions, including many that you don’t need. However, it does not have everything. At some point, you may want to do a particular task but can’t find a function for that. Well, that doesn’t mean you can’t do it. You may only need to take a few steps to get there. 🙂

With Google Apps Script, you can do a lot. It basically allows you to create your own functions, automate a lot of stuff, and even integrate Google Sheets with other third-party services.

The Google spreadsheet Apps Script tutorial in this article covers the basics of Google Apps Script, including several easy-to-follow examples. We will focus more on Google Sheets, though you can also write code in Google Docs, Forms, or a standalone script. 

What is Google Apps Script?

Google Apps Script (GAS) is a development platform that allows you to create applications that integrate with Google Workspace apps and services. 

It uses modern JavaScript as its scripting language. You don’t need to install anything. Google gives you an integrated code editor that allows you to edit your scripts within your browser. Your scripts execute on Google’s servers.

GAS plays a similar role in Google Sheets as Visual Basic for Applications (VBA) does in Excel. Both are used to extend functionality and integrate with other applications and third-party services.

What makes Google Apps Script useful?

Here are a few reasons why you would need Google Apps Script: 

  • Create Google Sheets custom functions.
  • Add custom menus, dialogs, and sidebars to Google Docs, Sheets, and Forms.
  • Interact with other Google Workspace apps and services, including Docs, Gmail, Calendar, Language, Docs, and more.
  • Automate tasks using triggers.
  • Build add-ons for Google Sheets, Docs, Slides, and Forms, and also publish them to the Google Workspace Marketplace.
  • Develop a user interface and publish it as a web app.
  • Connect with external relational databases (including Google Cloud SQL, MySQL, SQL Server, and Oracle) via the JDBC service.

What are Google Apps Script classes?

Classes are templates that encapsulate data with code for creating objects. Historically, JavaScript was class-free, so talking about classes may cause confusion. The classes described here are specific to Google implementations — Google refers to SpreadsheetApp, GmailApp, etc., as classes.

Google Apps Script provides several top-level classes. These main classes allow you to access features of other Google apps and services, for example:

  • Google Sheets can be accessed using SpreadsheetApp class
  • Google Docs can be accessed using DocumentApp class
  • Google Drive can be accessed using DriveApp class
  • Gmail can be accessed using GmailApp class
  • Language service can be accessed using LanguageApp class
  • And more

Apps Scripts also provides base classes. These allow you to access user info, such as email addresses and usernames, and also control script logs and dialog boxes. Some examples of base classes:

  • Browser – provides access to dialog boxes specific to Google Sheets.
  • Logger – allows the developer to write out a value to the execution logs.
  • Session – provides access to session information, such as the user’s email address (in some circumstances) and language setting.

In this Google Apps Script Sheets tutorial, we will also use some of the classes mentioned above. For example, we’ll use the SpreadsheetApp class to access Google Sheets’s functionalities and the LanguageApp class to access Google’s language service.

Note: In February 2020, Google introduced the V8 runtime for Apps Script, which supports classes. This new runtime lets you create your own classes, which provide a means to organize code with inheritance. Think of it as creating a blueprint from which copies can be made. 

Getting started with Google Apps Script

Enough intro — let’s dig in! 🙂

The best way to learn Google Apps Script is to write some code. Getting started is very straightforward — all you need is a Google account, a browser, and an internet connection.

To get started, go to Google Drive and create a new spreadsheet. Give your spreadsheet a name, for example, My First Script.

You can open the Apps Script editor by clicking Extensions > Apps Script from the menu (or Tools > Script editor if you can’t find the Extensions menu). 

Opening the Google Apps Script editor

This will launch the Apps Script editor in a separate tab in your browser.

How to use Google Apps Script Editor

Now, we’ll show you how to use the Apps Script editor. For example, how to rename your project, add a new function, and save your changes.

How to rename your project

Scripts are organized as projects. By default, the project name for your scripts embedded within the spreadsheet file you just created is “Untitled project”.

At the top left, you’ll see the project name. Click on it to rename it. A small window will appear, allowing you to enter a new project title.

Custom Google Apps Script string functions for translation

There is also a Code.gs file opened in the editor. It has a default function, which is blank, named myFunction()

function myFunction() {
  
}

How to add your first function

Delete the myFunction() code block so that your editor is now blank. Then, copy and paste the following code:

function writeHelloWorld() {
  var greeting = 'Hello world!';
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange('A1').setValue(greeting);
}

Your entire code will look like this:

An example hello world script

The above writeHelloWorld() function writes “Hello world!” to the spreadsheet. It demonstrates that, by using Apps Script, you can manipulate a spreadsheet. 

The code uses the SpreadsheetApp class to get an object representing the active sheet using the getActiveSheet() method. Then, it gets a single cell with the address A1 using the getRange() method. Another method, setValue(), is then called with a string argument to write to A1

How to save your changes

Notice that there is an orange circle icon on the left side of the Code.gs file name. It means your changes have not been saved yet. 

To save your changes, press Ctrl+S on your keyboard. Alternatively, you can click the disk icon (Disk icon). After that, the orange icon will be gone, and you’ll be able to run your script.

How to run Google Apps Script

Click the Run button to execute your function. For the first time you run the script, you will need to authorize it to access your data.

Google Apps Script authorization - reviewing permissions

Click the Review permissions button. Another pop-up will appear, asking you to select an account to continue. After that, you may see a warning screen saying “Google hasn’t verified this app“. Continue anyway — because, in this case, we know it’s safe. Then, allow the script to access your Google account.

Google Apps Script authorization - allowing access

Once authorized, the writeHelloWorld() function will execute, and you’ll see “Hello world!” in A1:

Google Apps Script example - Sheets manipulation

Google Apps Script examples

Now, let’s look at some more interesting examples using Apps Script.  

Connect to other Google apps using Google Apps Script

The following example shows that a GAS written in one app (Sheets) can be used to manipulate other Google apps (Docs). Though trivial and useless, this example demonstrates a very powerful feature of GAS!

Copy and paste the following function into your editor, then click the Run button to execute it.

function createDocument() {
  var greeting = 'Hello world!';
  
  var doc = DocumentApp.create('Hello_DocumentApp');
  doc.setText(greeting);
  doc.saveAndClose();
}

Once authorized, it will create a new Google Document with “Hello world!” written on it. 

Google Apps Script example - Google Docs manipulation

You may find it’s a bit inconvenient always having to open the editor when executing your code. A simple solution for that is to add a custom menu. 

You can add the code for the custom menu within the onOpen() function. A trigger will then execute your code inside this function every time you open the spreadsheet. Here’s an example:

function onOpen(e) {
  
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('My Custom Menu')
      .addItem('First item', 'function1')
      .addSeparator()
      .addSubMenu(ui.createMenu('Sub-menu')
          .addItem('Second item', 'function2'))
      .addToUi();
}
 
function function1() {
  SpreadsheetApp.getUi().alert('You clicked the first menu item!');
}
 
function function2() {
  SpreadsheetApp.getUi().alert('You clicked the second menu item!');
}

Note: The e parameter passed to the function is an event object. It contains information about the context that caused the trigger to fire, but using it is optional.

To test it, select the onOpen() function in the dropdown, then click the Run button. 

A custom menu code within the onOpen() function

You’ll see “My Custom Menu” in your spreadsheet menu, as shown in the following screenshot:

A custom menu in Google spreadsheet

The onOpen() function is one of GAS’s reserved function names. Whenever you open a document, a built-in trigger executes this function first. These built-in triggers are also called simple triggers and do not need user authorization.

Other reserved function names include onEdit(), onInstall(), onSelectionChange(e), onFormSubmit(), doGet(), and doPost(). Make sure you don’t use these as your function names.

Automate tasks using Google Apps Script trigger

GAS lets you create your own triggers. These triggers are also called installable triggers because you need to authorize them before use. 

With installable triggers, you can set your script to run at a certain event (when opening or editing a document, etc.) or on a schedule (hourly, daily, etc.).

Notice the following script. The getBitcoinPrice() function gets the data in the last 24 hours from the Bitstamp trading platform and outputs them in a sheet.

function getBitcoinPrice() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  
  // Get the sheet with the name Sheet1
  var sheet = spreadsheet.getSheetByName("Sheet1");
  var header = ['Timestamp','High','Low','Volume','Bid','Ask'];
 
  // Insert headers at the top row.
  sheet.getRange("A1:F1").setValues([header]);
 
  var url = 'https://www.bitstamp.net/api/ticker/';
 
  var response = UrlFetchApp.fetch(url);
 
  // Proceed if no error occurred.
  if (response.getResponseCode() == 200) {
    
    var json = JSON.parse(response);
    var result = [];
 
    // Timestamp
    result.push( new Date(json.timestamp *= 1000) );
 
    // High
    result.push(json.high);
    
    // Low
    result.push(json.low);
    
    // Volume
    result.push(json.volume);
    
    // Bid (highest buy order)
    result.push(json.bid);
    
    // Ask (lowest sell order)
    result.push(json.ask);
    
    // Append output to Bitcoin sheet.
    sheet.appendRow(result);
 
  } else {
 
    // Log the response to examine the error
    Logger.log(response);
  }  
}

Other than running it manually, you can create a trigger that runs the function, let’s say, every hour. And you can create a trigger either using a script or UI.

How to create a trigger using a script

To create a trigger that executes the getBitcoinPrice function every hour, copy and paste the following function to the editor:

function createTrigger() {  
  ScriptApp.newTrigger('getBitcoinPrice')
      .timeBased()
      .everyHours(1)
      .create();
}

Then, run the function manually by clicking the Run button. 

Creating a trigger using a script

Note: Do not run the createTrigger() function more than once, or you’ll end up creating multiple triggers instead of just one. 

Wait a few hours, and you should see the output in your spreadsheet, similar to the screenshot below:

The results after a few hours

You can see the list of triggers you created on the Triggers page, which can be opened from the left menu:

The Triggers menu

The Triggers page:

The Triggers page

How to create a trigger using UI

You can also create a trigger manually from the Triggers page. But before that, let’s add this new function to send bitcoin prices as an email with a PDF attachment.

function sendEmailBitcoinPricesPdfAttachment() {
  var file = SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF);
 
  var to = 'youremail@domain.com'; // change to yours
 
  GmailApp.sendEmail(to, 'Bitcoin prices', 'Attached prices in PDF', 
    { attachments: [file], name: 'BitcoinPrices via AppsScript' });
}

Then, on the Triggers page, click the Add Trigger button. A new pop-up will appear, allowing you to configure a new trigger.

Creating-a-new-trigger

To set a trigger that runs the sendEmailBitcoinPricesPdfAttachment() every day, use the following configuration: 

Configuring the trigger

Explanations of the options above:

  • Choose which function to run: select the sendEmailBitcoinPricesPdfAttachment() function we just created.
  • Choose which deployment to run: use Head to test code.
  • Select event source: select Time-driven to run the function on a schedule.
  • Select type of time-based trigger: select Day timer to run the function daily. Another dropdown will appear, allowing you to select the time of day when the function will run. Note: In the above screenshot, the time is set to 8 a.m. to 9 a.m., which means it will run at some time between these hours.
  • Failure notification settings: by default, you will be notified daily if the trigger fails to run. Optionally, you can change it to hourly, weekly, or even immediately.

When finished, don’t forget to click the Save button.

Custom function examples using Google Apps Script

Google Sheets offers hundreds of built-in functions like SUM, AVERAGE, CONCATENATE, and also more advanced functions like VLOOKUP, REGEXMATCH, and QUERY. When these aren’t enough for your needs, you can use GAS to write your own functions. 

Let’s look at a few examples of custom functions below.

Example #1. Custom numeric function using Google Apps Script

Here’s a simple custom function named AREAOFCIRCLE. The function calculates the area of a circle by taking a single numeric argument, which is the radius of the circle, and returns the area of a circle using the formula: PI * radius2.  It also validates that the radius is numeric and not less than 0.

/**Returns the area of ​​the circle from the specified radius input.
 * 
 * @param {number} radius
 * @return {number}
 * @customfunction
*/
function AREAOFCIRCLE (radius) {
  if (typeof radius !== 'number' || radius < 0){
    throw Error('Radius must be a positive number');
  }
 
  return Math.PI * Math.pow(radius, 2);
}

To use the function, write a few radius values in your spreadsheet. Then, type an equals sign followed by the function name and any input value. For example, type =AREAOFCIRCLE(A2) and press Enter. A nice thing here is that you can see the auto-complete shows the description of the new custom function:

A custom menu auto-complete

Copy the formula down, and you’ll see the following result:

A custom Google Apps Script numeric function

Notice that there’s an error in B5. That’s because xxxxx is not a numeric value. Thus, using =AREAOFCIRCLE(A5) returns an error message that we defined in the code.

Example #2. Custom string function using Google Apps Script

In the following example, you will see how custom functions can be used to access other Google services, such as the language service.

The following functions perform translations from English to other languages. Each of the functions takes a string argument and translates it to a different language: French, Spanish, or Italian.

function ENGLISHTOFRENCH(english_words) {
  return LanguageApp.translate(english_words, 'en', 'fr');
}
 
function ENGLISHTOSPANISH(english_words) {
  return LanguageApp.translate(english_words, 'en', 'es');
}
 
function ENGLISHTOITALIAN(english_words) {
  return LanguageApp.translate(english_words, 'en', 'it');
}

Example usage in a spreadsheet:

Custom-Google-Apps-Script-string-functions-for-translation

The functions seem to work well for a straightforward and non-idiomatic phrase. And you can use those functions to help you translate English words to other languages. However, it’s always best to check again with native speakers for the accuracy and quality of the translations.

Example #3. Custom date function using Google Apps Script

The following function returns an array of dates, which are the first day of each month for the given year, including their day names. This demonstrates that a custom function can also return a two-dimensional array.

function FIRSTDAYOFTHEMONTH(year) {
  var array = [];
 
  for (var m = 0; m <= 11; m++) {
    var firstDay = new Date(year, m, 1);
    
    var dayName = '';
 
    switch(firstDay.getDay()) {
      case 0: dayName = 'Sunday'; break;
      case 1: dayName = 'Monday'; break;
      case 2: dayName = 'Tuesday'; break;
      case 3: dayName = 'Wednesday'; break;
      case 4: dayName = 'Thursday'; break;
      case 5: dayName = 'Friday'; break;
      case 6: dayName = 'Saturday'; break;
    }
 
    array.push([(m+1) + '/1/' + year, dayName]);
  }
 
  return array;
}

Type in a cell, for example, =FIRSTDAYOFTHEMONTH(2021) in A1. You’ll see a result like this:

A custom Google Apps Script date function

Example #4. Custom web function for importing CSV using Google Apps Script

Suppose you want to import CSV data from a published online file. Google Sheets has a built-in function called IMPORTDATA for that. But when doing the import, you may want to add some filters. For example, to exclude several columns. In this case, you can use the IMPORTDATA in combination with the QUERY function to give you more options. 

Another alternative — you can write your own function using GAS to avoid writing several functions in one cell. Here’s an example:

function CUSTOMCSVIMPORT(url, columns) {
 
  var csvContent = UrlFetchApp.fetch(url).getContentText();
  var csvData = Utilities.parseCsv(csvContent);
  
  // Remove all white spaces, change to lower case, and split.  
  var requiredColumns = columns.split(",");
  
  // Get the indexes of required columns
  var indexesOfRequiredColumns = [];
 
  if (requiredColumns.length > 0) {
    for (var i = 0; i < csvData[0].length; i++) {
      if (requiredColumns.includes((csvData[0][i]))) {
        indexesOfRequiredColumns.push(i);
      }
    }
  }
 
  if (indexesOfRequiredColumns.length > 0) {
    return csvData.map(r => indexesOfRequiredColumns.map(i => r[i]));
  }
 
  return csvData;
}

The above function allows you to import a CSV file from a URL and choose only a few columns to import. 

The function has two parameters: url and columns. The second parameter (columns) accepts column names, each concatenated with a comma, for example: “columnname1,columnname2,...”

Example usage in a spreadsheet

In the following screenshot, you can see that only the columns specified in B2 are returned in the spreadsheet:

A custom Google Apps Script function for importing CSV data 

  • B1 cell contains the URL of a CSV file
http://samples.openweathermap.org/storage/history_bulk.csv?appid=b1b15e88fa797225412429c1c50c122a1 
  • B2 cell contains the columns to import   
dt,dt_iso,city_name,temp_min,temp_max,weather_main,weather_description

Can I use custom functions with ARRAYFORMULA?

You can’t nest custom functions with ARRAYFORMULA, but, you can modify your function to input and return a range in the form of a two-dimensional array. This will also optimize the performance of your spreadsheet, since each custom function run requires a call to the Apps Script server. The more custom functions calls are sent, the slower the performance of your spreadsheet will be. 

Here is an example of a simple custom function that converts Fahrenheit to Celsius:

function FtoC(input) {
  return (input - 32) * 0.5556;
}
A simple custom function that converts Fahrenheit to Celcius

We modified it to accept both a single cell and a range of cells, as follows:

function FtoC(input) {
  return Array.isArray(input) ?
   input.map(row => row.map(cell => (cell - 32) * 0.5556)) :
      (input - 32) * 0.5556;
}

So, now you can type in =ftoc(A2:A5) and get the desired outcome.

Custom function that returns a range of cells

Google Apps Script alternative: Coupler.io

Coding your own GAS function for importing data (as shown earlier with the CUSTOMCSVIMPORT function) may require a lot of effort. You’ll need to test various scenarios, try different filtering criteria, and so on.

If you’re looking for a convenient solution that is powerful and does not require any coding, you may want to try Coupler.io. It’s an integration tool that allows you to import data from CSV and other popular data sources into Google Sheets. 

Coupler.io also offers more features than the IMPORTDATA function does. For a detailed comparison, you may want to check out this comparison table: IMPORTDATA vs. Coupler.io.

Here’s an example screenshot of selecting CSV data source in Coupler.io:

Coupler.io data source list

Simply copy and paste the CSV URL to import:

Coupler.io - Specifying the URL of a CSV file to import

Optionally, you can specify which fields to import and even skip some rows if you’d like to:

Coupler.io - Options to filter columns and skip rows

And more interestingly, you can set up an automatic data refresh on a schedule:

Coupler.io - Automatic data-refresh

Google Apps Script limitations

As GAS runs on Google’s server, Google sets limits on its execution, such as: 

  • A script cannot run continuously for more than 6 minutes. So, for example, if you use “looping” in your function, ensure that it is bug-free and will not cause an endless execution. Also, avoid handling a huge dataset that may cause the script to run for more than 6 minutes.
  • A custom function cannot execute for more than 30 seconds. So, avoid handling large external data using custom functions. Otherwise, you may see a “Maximum execution time exceeded” error.

Please note that the above limitations may change in the future. You can find the complete list of GAS limitations here.

How can I learn more about Google Apps Script 

In this Google Apps Script tutorial, you’ve learned how to create custom functions, custom menus, and access to other Google apps and services. However, GAS is powerful, and you can do a lot more, such as creating add-ons, publishing web apps, and connecting to external databases. 

If you want to learn more about Google Apps Script, one common suggestion is to learn JavaScript and follow the numerous tutorials available on the internet. Well, there is no doubt that the number of tutorials on the internet is huge and they can be overwhelming.

Therefore, we suggest you start with the following sources:  

  • Documentation on Apps Script by Google. 
  • Samples, codelab, video tutorials, articles, and other learning resources for Apps Script by Google.

And here are some other free and useful resources:

  • Eloquent JavaScript – ebook by Marijn Haverbeke; it’s free digitally.
  • Apps Script Blastoff! – free introductory Apps Script course by Ben Collins.
  • Stackoverflow entries for Google Apps Script – ask questions here.
  • Apps Script open issues – post any issues (or enhancement requests) here.

Happy learning and enjoy! 🙂

  • Fitrianingrum Seto

    Technical content writer with a strong interest in data. My background is in software engineering. I’ve developed software, worked with data, and been involved in SaaS product development. I love producing content that adds value to businesses and helps readers.

Back to Blog

Focus on your business

goals while we take care of your data!

Try Coupler.io

Понравилась статья? Поделить с друзьями:
  • Атсефенак таблетка инструкция по применению взрослым от чего помогает
  • Инструкция по эксплуатации автосигнализации старлайн а62
  • Руководство по медицинскому обеспечению вооруженных сил 2017 скачать
  • Цикловита инструкция по применению цена для чего применяется таблетки подросткам
  • Мануал rav4 на русском