If matching content move to new sheet - javascript

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?

Related

Why did my code break when I copied it over from one workbook into another?

So I just had someone on Fiverr write this cote for me and it works great! I had him write it on a copy of the one I needed for work. when I copied into the one that was assigned to me at work it breaks at line 40. Any and all fixes would be great!!
I think it doesn't have the correct sheet selected so it is kicking back a null error
TypeError: Cannot read property 'getRange' of null
This is the error I get after running it. Again tho this works on the workbook I had him design it in but I need to know how to fix it.
// If you want to change any tab's name, also change it from here.
var ss = SpreadsheetApp.getActive();
var tem = ss.getSheetByName("Template");
var frm = ss.getSheetByName("Form Responses 1");
var cde = ss.getSheetByName("Code");
//---------------------------------------------------------------------------------------------------------------------------------------
lr = frm.getLastRow();
// Logger.log(lr)
for(i=4; i<=lr; i++){
//----------These are values from the Form Responses tab, 2,1, 3, 4, 5 ... represent the column numbers.
// For example, date is in column 1, so var date = frm.getRange(i,1).getValue();
// store name is in column 3, so var store = frm.getRange(i,3).getValue();
var tabName = frm.getRange(i,2).getValue();
var date = frm.getRange(i,1).getValue();
var store = frm.getRange(i,3).getValue();
var add1 = frm.getRange(i,4).getValue();
var add2 = frm.getRange(i,5).getValue();
var add3 = frm.getRange(i,6).getValue();
var zip = frm.getRange(i,7).getValue();
var city = frm.getRange(i,8).getValue();
var state = frm.getRange(i,9).getValue();
var phone = frm.getRange(i,10).getValue();
var email = frm.getRange(i,11).getValue();
var po = frm.getRange (i,16).getValue();
var glowHeart = frm.getRange(i,17).getValue();
var glowSquare = frm.getRange(i,18).getValue();
var rainHeart = frm.getRange(i,19).getValue();
var rainSquare = frm.getRange(i,20).getValue();
///-----The following line of code checks if there is already a tab for a store name, if not create new.
if(ss.getSheetByName(tabName)==null && tabName!==""){
var create = ss.insertSheet(tabName);
}
if ( tabName==""){
break;
}
///- - - - - - Now write the row values to the template tab.
tem.getRange("B2").setValue(tabName); // cell B2 is set to name
tem.getRange("B3").setValue(store);// cell B3 is set to store name and so on
tem.getRange("F3").setValue(date);
tem.getRange("B5").setValue(add1);
tem.getRange("B6").setValue(add2);
tem.getRange("B7").setValue(add3);
tem.getRange("B8").setValue(zip);
tem.getRange("B9").setValue(city);
tem.getRange("B10").setValue(state);
tem.getRange("B12").setValue(phone);
tem.getRange("B13").setValue(email);
tem.getRange("C17").setValue(glowHeart);
tem.getRange("C18").setValue(glowSquare);
tem.getRange("D17").setValue(rainHeart);
tem.getRange("D18").setValue(rainSquare);
tem.getRange("F4").setValue(po);
/// Once the template is filled, it is moved to the newly created tab
moveVal(tabName)
// After that, new file is created for that
createNewFile(tabName)
/// These lines clear the template once done.
tem.getRange("B2").setValue("");
tem.getRange("B3").setValue("");
tem.getRange("F3").setValue("");
tem.getRange("B5").setValue("");
tem.getRange("B6").setValue("");
tem.getRange("B7").setValue("");
tem.getRange("B8").setValue("");
tem.getRange("B9").setValue("");
tem.getRange("B10").setValue("");
tem.getRange("B12").setValue("");
tem.getRange("B13").setValue("");
tem.getRange("C17").setValue("");
tem.getRange("C18").setValue("");
tem.getRange("D17").setValue("");
tem.getRange("D18").setValue("");
tem.getRange("F4").setValue("");
}
}
// This fucntion creates new tabs
function moveVal(tabName) {
var ss = SpreadsheetApp.getActive();
var spreadsheet = ss.getSheetByName("Template");
//var spreadsheet = SpreadsheetApp.getActive();
spreadsheet.getRange('A1:G29').activate();
ss.setActiveSheet(ss.getSheetByName(tabName), true);
ss.getRange('Template!A1:G29').copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false);
ss.setActiveSheet(ss.getSheetByName('Template'), true);
spreadsheet.getRange('F9').activate();
};
// This fucntion creates new files.
function createNewFile(tabName){
var ss = SpreadsheetApp.getActive();
var cde = ss.getSheetByName("Code");
var newF = SpreadsheetApp.create(tabName);
var dd = newF.getId();
Logger.log(dd)
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheetByName("Price");
var destination = SpreadsheetApp.openById(dd);
sheet.copyTo(destination);
destination.getSheetByName("Copy of Price").setName("Price");
var sheet = source.getSheetByName("Template");
var destination = SpreadsheetApp.openById(dd);
sheet.copyTo(destination);
destination.getSheetByName("Copy of Template").setName(tabName);
destination.getSheetByName("Sheet1").getRange('D26').activate();
destination.deleteActiveSheet();
destination.getSheetByName(tabName).activate()
destination.setActiveSheet(destination.getSheetByName('Price'), true);
destination.getActiveSheet().hideSheet();
sourceFileId =dd;
//targetFolderId = "xxxxxxxxxxxxxx";
////////////////////////////// You can change the cell from here. ////////////
targetFolderId = cde.getRange("G3").getValue(); // This gets the folder's id from cell G3 in Code tab
///..........................................................................................
//Logger.log(targetFolderId)
moveFiles(sourceFileId,targetFolderId)
}
// THis fucntion moves the file to the specified folder.
function moveFiles(sourceFileId,targetFolderId) {
var file = DriveApp.getFileById(sourceFileId);
var folder = DriveApp.getFolderById(targetFolderId);
file.moveTo(folder);
}
It breaks right when it gets to these lines
tem.getRange("B2").setValue(tabName); // cell B2 is set to name
tem.getRange("B3").setValue(store);// cell B3 is set to store name and so on
tem.getRange("F3").setValue(date);
tem.getRange("B5").setValue(add1);
tem.getRange("B6").setValue(add2);
tem.getRange("B7").setValue(add3);
tem.getRange("B8").setValue(zip);
tem.getRange("B9").setValue(city);
tem.getRange("B10").setValue(state);
tem.getRange("B12").setValue(phone);
tem.getRange("B13").setValue(email);
tem.getRange("C17").setValue(glowHeart);
tem.getRange("C18").setValue(glowSquare);
tem.getRange("D17").setValue(rainHeart);
tem.getRange("D18").setValue(rainSquare);
tem.getRange("F4").setValue(po);

How to extract, clearcontent and import data using Google-Appscript?

I'm current working with merge file from the same spreadsheet (please see the script below).
function myFunction() {
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var s1 = sheet.getSheetByName('SOURCE A')
var s2 = sheet.getSheetByName('SOURCE B')
var s3 = sheet.getSheetByName('SOURCE C')
var s4 = sheet.getSheetByName('Destination')
var s1values = s1.getRange(1,1,s1.getLastRow(), s1.getLastColumn()).getValues();
var s2values = s2.getRange(1,1,s2.getLastRow(), s2.getLastColumn()).getValues();
var s3values = s3.getRange(1,1,s3.getLastRow(), s3.getLastColumn()).getValues();
var s4values = [];
s4values = s1values.concat(s2values,s3values);
s4.clearContents().getRange(1, 1, s4values.length, s4values[0].length).setValues(s4values);
}
The aim is to concat a multiple data from different spreadsheet source and also extract only the range that I needed (eg. A:B, E:J, K:P). Let say in the destination sheet I have some formula in Column K and so on, what I want now is to clearcontent the range of A:O every time the script run and import the concatenated data in to the said range.
I'm sharing to you the sample data source that I needed to combine and Import only the range of "A:D, Y:Z, AZ:BB" to Destination
Here's the link:
Source 1, Source 2, Source 3.
For destination link:Destination

Spreadsheet to copy informations from another sheets - 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.

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);
}

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