F
F
facepalmzone2022-01-12 12:09:23
Google Apps Script
facepalmzone, 2022-01-12 12:09:23

How to autosave from multiple sheets to one in Google Sheets?

Tell me how to change the code in Apps Script so that the trigger saves information from the cells I need not from one sheet, but from three at once in Google Sheets, namely:
Cells Sheet1 → Sheet5
Cells Sheet2 → Sheet5
Cells Sheet3 → Sheet5

What I Wrote works only for one. you cannot insert multiple book.getSheetByName into a function

function saveData() {
  const book = SpreadsheetApp.openById(
    'ID документа'
  );
  const sheet = book.getSheetByName('Лист1');
  const values = sheet.getRange('A1:H4').getValues();
  book.getSheetByName('Лист5').appendRow([new Date(), values[0][0], values[0][1], values[0][2], values[0][3], values[0][4], values[0][5], values[0][6], values[0][7]]);
  console.info(`saveData was called successful`);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Ivanov, 2022-01-12
@facepalmzone

Well, for example, like this

function saveData2() {
  const book = SpreadsheetApp.openById(
    '1FUSSiDQoXyvKXfzYydoUUfcCGYq_TskpRiwfb28_1Z0'
  );
  const date = new Date();
  const sheetTotal = book.getSheetByName('TOTAL');
  const sheetGOOG = book.getSheetByName('NASDAQ:GOOG');
  const valuesGOOG = sheetGOOG.getRange('C3:U3').getValues().map(row => [date, 'NASDAQ:GOOG', ...row]);
  appendData_(sheetTotal, valuesGOOG);
  const sheetDIS = book.getSheetByName('NYSE:DIS');
  const valuesDIS = sheetDIS.getRange('C3:U3').getValues().map(row => [date, 'NYSE:DIS', ...row]);
  appendData_(sheetTotal, valuesDIS);
  console.info(`saveData was called successful`);
}

function appendData_(sheet, values) {
  if (sheet.getLastRow() === sheet.getMaxRows())
    sheet.appendRow([]);
  sheet.getRange(sheet.getLastRow() + 1, 1, values.length, values[0].length)
    .setValues(values);
}

  1. Grab the 'NASDAQ:GOOG' sheet
  2. Get data from 'C3:U3'
  3. Calling appendData_
  4. Repeat for leaf 'NYSE:DIS'

saveData2set for daily trigger
Result
61ded0ce1b9dd206623233.png
Example added to Table from this answer https://qna.habr.com/answer?answer_id=1834719#answ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question