Spreadsheet to copy informations from another sheets - Javascript - javascript

I'm looking way to create easier version of my code. I want to, copy information from every sheet to one sheet. First informations from first sheet, then below from second sheet etc. Now I have every each code for sheet, it is any way to make it easier? What code should use? Below my code and drawing with explanation.
function copy() {
var ur = SpreadsheetApp.getActiveSpreadsheet(); // sheet where we copy data
var urgents = ur.getSheetByName("List");
var lastRow = urgents.getLastRow();
var range = urgents.getRange("A2:B");
range.clear(); // every time script clear data
var importsh = SpreadsheetApp.openById('115nqlMpW3dhI-adpWvir5RZeayM01HqvjOcDc2_yLvQ');
var imbrak = importsh.getSheetByName('List_1'); // sheet from we copy data
var imbrak2 = importsh.getSheetByName('List_2'); // sheet from we copy data
var lastcol = importsh.getLastColumn();
var lastcol2 = imbrak2.getLastColumn();
var last = imbrak.getLastRow();
var last2 = imbrak2.getLastRow();
var urlast = last;
var urlast2 = last2;
var data = imbrak.getRange("A2:B"+last).getValues();
var data2 = imbrak2.getRange("A2:B"+last2).getValues();
urgents.getRange("A2:B"+last).setValues(data);
urgents.getRange(getFirstEmptyRowWholeRow3(),1,last2-1,2).setValues(data2);
}
Regards

How about this modification? Please think of this as one of several answers.
Modification points :
Use an array for sheet names.
By this, when it increases the number of sheets, you can use this script by importing the sheet names to the array.
All data of each sheets is imported to an array.
By this, the data can be imported to the destination sheet by one call of setValues().
Modified script :
function copy() {
var ur = SpreadsheetApp.getActiveSpreadsheet(); // sheet where we copy data
var urgents = ur.getSheetByName("List");
var lastRow = urgents.getLastRow();
var range = urgents.getRange("A2:B");
range.clear(); // every time script clear data
// Added
var importsh = SpreadsheetApp.openById('115nqlMpW3dhI-adpWvir5RZeayM01HqvjOcDc2_yLvQ');
var sheets = ['List_1', 'List_2']; // Please import sheet names here.
var data = [];
sheets.forEach(function(e){
var s = importsh.getSheetByName(e);
var values = s.getRange("A2:B"+s.getLastRow()).getValues();
Array.prototype.push.apply(data, values);
});
urgents.getRange(2, 1, data.length, data[0].length).setValues(data); // Please confirm this range.
}
Note :
Please confirm the range of urgents.getRange(2, 1, data.length, data[0].length).setValues(data);. Because I have no information about getFirstEmptyRowWholeRow3().
In the current range, the data is imported to "A2:B".
If I misunderstand your question, please tell me. I would like to modify.

Related

If matching content move to new sheet

I am writing a script that looks through a list of suppliers, then needs to create a new sheet for each of them and import the information for that supplier into that sheet.
So far, I have the following:
function getData() {
var masterSS = SpreadsheetApp.getActiveSpreadsheet() || SpreadsheetApp.openById("xxx");
var supSS = masterSS.getSheetByName("Suppliers");
masterSS.setActiveSheet(supSS)
var supSR = 2;
var supNoRows = supSS.getLastRow() - 1;
var supRange = supSS.getRange(supSR, 1, supNoRows, masterSS.getLastColumn());
var supData = supRange.getValues();
var orderSS = masterSS.getSheetByName("Orders");
var orderData = orderSS.getRange("A2:AB").getValues();
var templateSS = masterSS.getSheetByName("Template");
supData.forEach(function(name) {
var newSheet = masterSS.insertSheet(name, {template: templateSS});
console.log(name)
});
}
This is working as intended and is creating a sheet for each supplier listed on the Supplier sheet. I then need it to look through a range on a sheet called Orders, and if A2:A matches the supplier name used to create the new sheet, import that row to the newly created sheet.
I can't figure out quite how to get this working, as I would need to do it as each sheet is created. Anyone able to point me in the right direction?

Reading multiple spreadsheets in google app script

I'm trying to get all text from a specific cell of all spreadsheets in a folder. My current issue is I can only read them in as a file type which doesn't allow me to access the getRange() function.
Here's my code so far.
function createLog() {
var folder = DriveApp.getFolderById("id#");//not placing actual id for privacy
var contents = folder.getFiles();
var data; //array for relevant text
var file;
var d = new Date();
var log = SpreadsheetApp.create("Events log "+d.getMonth()+"/"+d.getDay());
while(contents.hasNext()) {
file = contents.next();
file.getRange("A6");//error is here because it is a file type not a spreadsheet
}
for(var i =0; i<contents.length;i++){
log.getRange(0,i).setValue(data[i]);
}
}
Once you have the list of files you need to open them with SpreadsheetApp. Then you can work on Spreadsheet using the Sheet and Range functions.
var spreadsheet = SpreadsheetApp.openById(file.getId());
var sheet = spreadsheet.getSheetByName('your sheet name');
var value = sheet.getRange("A6");
See:
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app
https://developers.google.com/apps-script/reference/drive/file#getId()
Cameron's answer is correct but I suggest to open spreadsheets by ID instead of names because in Google Drive many files can have the same name...
Below is a simplified demo code to test the idea and a few comments to highlight what needs to be adjusted
function createLog() {
var folder = DriveApp.getFolderById("0B3###############ZMDQ");//not placing actual id for privacy
var contents = folder.getFilesByType(MimeType.GOOGLE_SHEETS);
var data; //array for relevant text
var fileID,file,sheet;
var data = [];
var d = new Date();
var log = SpreadsheetApp.create("Events log "+d.getMonth()+"/"+d.getDay());
while(contents.hasNext()) {
file = contents.next();
Logger.log('Sheet Name = '+file.getName());
fileID = file.getId();
sheet = SpreadsheetApp.openById(fileID).getSheets()[0];// this will get the first sheet in the spreadsheet, adapt to your needs
data.push([sheet.getRange("A6").getValue()]);// add a condition before this line to get only the data you want
}
log.getActiveSheet().getRange(1,1,data.length, data[0].length).setValues(data);
}

Storing an Array in Google App Script and Printing an Array to Google Sheets Column

I'm working on a Google Sheets and I'm trying to store an column of integers in an array, then clear a column on the sheet and then print the array of integers to a column on the sheet. Please see below for code...
function myFunction1() {
//Declaring the Active Sheet
var mySheet = SpreadsheetApp.getActiveSheet();
//Declaring the range that will make up the Array
var myRange = mySheet.getRange("E10:E328");
//Declaring Array
var myArray = [[myRange.getValues()]];
//Clearing a range on the Google Sheet
mySheet.getRange('A10:A328').clearContent();
//Printing Array to Google Sheet
mySheet.getRange(15, 5).setValues([myArray]);
}
The above code runs without any errors but does not print my array to the sheet. I've been working on this for a while and have used the following articles to try to fix it...
https://productforums.google.com/forum/#!topic/docs/t99laH0rFc0
Incorrect Range Height - Google Script
Writing 1D array into a sheet column in Apps Script
https://developers.google.com/apps-script/reference/spreadsheet/range#setvaluesvalues
Common errors that i have had when writing the code up to this point is, "Incorrect Range Height" and "Cannot convert Array to Object[][]".
How would i fix this so that my Array prints to the column on the sheet?
Thanks for your time! Any help on this would be great!!
You're making it a bit more complex than you have to.
function myFunction1() {
//Declaring the Active Sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var mySheet = ss.getActiveSheet();
//Declaring the range that will make up the Array
var myArray = mySheet.getRange("E10:E328").getValues();//already in an array
//Clearing a range on the Google Sheet
mySheet.getRange('A10:A328').clearContent();
//Printing Array to Google Sheet
mySheet.getRange(15, 5).setValues(myArray); //already in an array don't need brackets
}
// Write data in cell G1, H1, I1
function arrayPlay() {
var newArray = [];
// Variable that saves the data from G1->I1.
var cellIn1 = ("G1");
var cellIn2 = ("H1");
var cellIn3 = ("I1");
var sheet = SpreadsheetApp.getActiveSheet();
// Defines where the data is recieved. (G1, H1, I1)
var cellOut1 = sheet.getRange(cellIn1);
var cellOut2 = sheet.getRange(cellIn2);
var cellOut3 = sheet.getRange(cellIn3);
// Recieve the data from those cells
var data1 = cellOut1.getValue();
var data2 = cellOut2.getValue();
var data3 = cellOut3.getValue();
// Puts the data in the Array. (newArray)
newArray.push(data1, data2, data3)
// Presents the data in Cell 1-3 (A1, A2, A3)) Downwards
sheet.appendRow([newArray[0]]);
sheet.appendRow([newArray[1]]);
sheet.appendRow([newArray[2]]);
// Presents the data in Cell 1-3 (A1, B1, C1) Sideways
sheet.appendRow([newArray[0], newArray[1], newArray[2]]);
Logger.log(newArray);
}
It is hard to tell exactly what you are trying to do. But if you are trying to replace column A with column E, just do this:
function myFunction1() {
var mySheet = SpreadsheetApp.getActiveSheet();
var myRange = mySheet.getRange("E10:E328").getValues();
mySheet.getRange('A10:A328').setValues(myRange);
}

Google Spreadsheet On change write log to another sheet

please can anyone help with one problem in google spreadsheet?
After changing value in one concrete collumn in sheet "Venues", I would like to write log about name and time, when this value was changed. But I can't really realize , if I am working with spreadsheet "Venues" or some other. I am not very into class structure of google API for Spreadsheet. So can anyone help with it?
I need:
run eventhandler on event when value in appropriate column in appropriate sheet ("Venues") is changed
get value from collumn name from this sheet
get actual time
write name and time to another sheet called "status_history" to last row (like append)
My hard try to write something: (but that is really bad code)
function onEdit(event)
{
var sheet = event.source.getActiveSheet();
var cell = sheet.getActiveCell();
var cellR = cell.getRow();
var cellC = cell.getColumn();
var cellValue = cell.getValue();
var cellCName = cell.getColumn()-1; //column with names
var name = sheet.getRange(cellR, cellCName).getValue();//get name
var active_spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
if(sheet.getName() == "Venues"){
if(cellC == 5 /* if correct collumn was changed */){
var output_sheet = active_spreadsheet.getSheetByName("status_history");
var lastRow = output_sheet.getLastRow();
var lastRange = output_sheet.getRange(lastRow, 1)
//HERE: write value: name
var lastRow = output_sheet.getLastRow();
var lastRange = output_sheet.getRange(lastRow, 2)
//HERE: write value: time
}
}
}
You were getting there. Just a couple of tweaks needed.
With onEdit functions, you need to keep things fast, since they get invoked so often.
Rely on the event information as much as you can, avoiding calls to Google Apps services.
If you must use a service, do it only when you absolutely need to - for example, wait until you are past the if statements that tell whether you are in a cell you want to log before calling SpreadsheetApp.getActiveSpreadsheet().
The API is rich, so look for functions that will let you reduce the number of system calls you make - see how appendRow() replaced multiple statements, for example.
Here's your function after a code inspection:
function onEdit(event) {
var sheet = event.range.getSheet();
if(sheet.getName() == "Venues"){
// correct sheet
var cell = event.range;
//var cellR = cell.getRow(); // not used at this time
var cellC = cell.getColumn();
var cellValue = event.value;
if (cellC == 5) {
// correct column
var name = cell.offset(0,-1).getValue(); // get name, 1 column to left
var time = new Date(); // timestamp
var active_spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var output_sheet = active_spreadsheet.getSheetByName("status_history");
output_sheet.appendRow([name,time]);
}
}
}
You could make it more flexible and portable by using column names to test conditions. Take a look at Adam's answer here.

Google spreadsheet ImportRange - need to improve my workaround

I am pretty new to this forum and also to the google scripts. I have never actually learned JavaScript or any other programming language, however I was forced to start using then since the time I chose the google apps as my main platform for my small business.
My problem is in google ImportRange function limitation to 50 on every spreadsheet. I created a model, where every customer has his own spreadsheet with his personal data, deadlines, etc. located in his own folder in google drive.
I also created a spreadsheet called "Organizer", Organizer has two functions -
1) create automatic correspondention using autoCrat script,
2) show deadlines for every costumer and sort them by priority.
So i need to be able to share / import / copy data from all customer spreadsheets to the "Organizer". Because there are 50+ costumer spreadsheets, I had to give up on ImportRange function and instead of that I am using a simple script to copy files from every spreadsheet directly:
function ImportDataRange() {
// rown number.1
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Databaze");
var range = sheet.getRange(2, 1)
var id = range.getValue()
var ssraw = SpreadsheetApp.openById(id);
var sheetraw = ssraw.getSheetByName("Raw");
var range = sheetraw.getRange("A2:AB2");
var data = range.getValues();
sheet.getRange("B2:AC2").setValues(data)
// row number.2
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Databaze");
var range = sheet.getRange(3, 1)
var id = range.getValue()
var ssraw = SpreadsheetApp.openById(id);
var sheetraw = ssraw.getSheetByName("Raw");
var range = sheetraw.getRange("A2:AB2");
var data = range.getValues();
sheet.getRange("B3:AC3").setValues(data)
}
This script actually works well, but problem is, when I want to add new costumer spreadsheet to "Organizer" using this method, I have to manually add new copy of whole code for every new row and also change the output range of imported data and location of source file ID in "Organizer".
Does anybody know some kind of workaroud, which will help me to add new rows / costumer data easier / automatically ?
Thank you for your help!
You are going to want to use a loop of some sort. I haven't tested the code below, but based on your example, I think this should work for you.
function ImportOtherSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Databaze");
// Get the first column
// lastRow() - 1 because we're starting at row 2
var sheetIds = sheet.getRange(2, 1, sheet.getLastRow() - 1);
// For each ID in the id column
for (var i = 0; i < sheetIds.length; i++) {
var id = sheetIds[i]; // Get the id from the Array
// Get the new sheet, range and values
var ssraw = SpreadsheetApp.openById(id);
var sheetraw = ssraw.getSheetByName("Raw");
var range = sheetraw.getRange("A2:AB2");
var data = range.getValues();
// Get the local range, and write the values
sheet.getRange(i + 1, 2, 1, data[0].length).setValues(data)
}
}
As you learn more about GAS and JS, take advantage of MDN and the GAS Documentation
I took the fooby´s code and after long trial-and-error procedure I came with code that is working for me, so if anyone is interested, here it is:
function ShowDataFromOtherSheet() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Databaze");
var ids = sheet.getRange(2, 1, sheet.getLastRow() - 1).getValues();
for (var i = 0; i < ids.length; i++) {
var id = ids[i];
var ssraw = SpreadsheetApp.openById(id);
var sheetraw = ssraw.getSheetByName("Raw");
var range = sheetraw.getRange("A2:AB2");
var data = range.getValues();
sheet.getRange(i + 2, 2, 1, data[0].length).setValues(data)
}
}
And thank you fooby - i would not make it without your help!

Categories