A
A
Andrey_782019-04-19 18:49:48
Google Apps Script
Andrey_78, 2019-04-19 18:49:48

How to sequentially write columns from different google sheets into one array (Google apps script)?

I pass data through a variable in a loop, then, as planned, an array of 3 sheets should be written, but for some reason the array of only the last sheet remains, what is my mistake?

function Flat_data() {

var a = ["Sheet #1", "Sheet #2", "Sheet #3"];
var index;
for (index = 0; index < a.length; ++index) {
   /// Logger.log(a[index]);

var SOURCESHEET = SpreadsheetApp.openById("ID таблицы с которой беруться данные").getSheetByName(a[index]); 


var source_last_row = SOURCESHEET.getLastRow();

var source_range1 = SOURCESHEET.getRange("G6:I"+(source_last_row)).getValues();
var source_range2 = SOURCESHEET.getRange("J6:L"+(source_last_row)).getValues();
var source_range3 = SOURCESHEET.getRange("N6:P"+(source_last_row)).getValues(); 
var source_range4 = SOURCESHEET.getRange("Q6:S"+(source_last_row)).getValues(); 

var targetvalues = [];
targetvalues = source_range1.concat(source_range2,source_range3,source_range4);

}  
Logger.log(targetvalues);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Samokhin, 2019-04-20
@hda1

1. With each iteration of the loop, targetvalues ​​is re-created. It is necessary to take out its description for a cycle.
2. With each iteration of the loop, targetvalues ​​is assigned a new value, regardless of its contents. You need to add a new value to the old value.

R
Roman, 2019-04-24
@JohnnyBravo7

function Flat_data() {

var a = ["Sheet #1", "Sheet #2", "Sheet #3"];
var total = [];
var index;
for (index = 0; index < a.length; ++index) {
   /// Logger.log(a[index]);

var SOURCESHEET = SpreadsheetApp.openById("ID таблицы с которой беруться данные").getSheetByName(a[index]); 


var source_last_row = SOURCESHEET.getLastRow();

var source_range1 = SOURCESHEET.getRange("G6:I"+(source_last_row)).getValues();
var source_range2 = SOURCESHEET.getRange("J6:L"+(source_last_row)).getValues();
var source_range3 = SOURCESHEET.getRange("N6:P"+(source_last_row)).getValues(); 
var source_range4 = SOURCESHEET.getRange("Q6:S"+(source_last_row)).getValues(); 

var targetvalues = [];
targetvalues = source_range1.concat(source_range2,source_range3,source_range4);
total.push(targetvalues);
}  
Logger.log(total);
}

The logic in your script is slightly broken.
You don't have storage where you write without deleting.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question