Concatenate tables in one and insert it in Google Spreesheet - javascript

I've got this basic script for Google Sheets, in G.Script
var a = [['1','2']];
for (var i = 0; i <5; i++){
var range = sheet.getRange("A"+i+":B"+i);
range.setValues(a);
}
As you can see, I write 5 times the table "a" in the sheet. What I'd like in concatenate all the tables "a" in one table and write this table, once in the sheet.
I've tried with concat(), but it does not work. So maybe I don't use it properly.
Could you please help me ?
Many thanks
B.

I recommend that you create your spreadsheet range based on the size of your array "a". Rather than creating a cell range such as A1:B5, I recommend using number values to define the range that you would like to update.
Also, updates to Google Sheets run much faster if you update an entire range at one time.
function myFunction() {
var data = [];
data.push([1,2]);
data.push([2,3]);
data.push([3,4]);
if (data.length > 0) {
SpreadsheetApp.getActiveSheet()
.getRange(1,1,data.length,data[0].length)
.setValues(data);
}
}

Related

I want to search a text within a cell range and return the value to the left of the cell (Google App Script)

I am trying to write a script to organize a large quantity of data.
I am a newbie and would really need help in this:
Sample Sheet
It needs to find the word (e.g. Nike) from the range B2 to E3 and display the cell value left of the found cell under column I for Nike, same goes for columns J(Fila) and K(New Balance), please see attached screenshot.
I tried for with if then statement and i dont think i was doing it correctly at all.
Thanks in advance.
https://developers.google.com/apps-script/guides/sheets Will guide you on using the information needed to edit/make Google App spreadsheets
So editing the values would just have to change the for loop for that.
Since you're wanting certain ranges, just change where the for loop starts.
for(int i = 0; i < /*data of spreadsheet*/; i++) {
data[1][1] = B2
data[1][2] = B3
}
Would be an example
data[1][1] = Shoes
data[1][2] = Nike/Fila/New Balance
data[2][1] = Pants

Google apps script - Mapping arrays

I am working on a project where I take multiple column/row inventory sheets and turn them into a multi-row/2-column format for order picking.
I have a switch for selecting the appropriate inventory sheet and a map() function that copies the imported information from the inventory DataRange().
However, not all the data is in consistent columns. What I would like to do is find an expression that maps the next column in if the column it was mapping has a zero or "" value.
I won't give you the full body of code unless you need it, but hopefully just the important parts.
This is what I have:
var source = SpreadsheetApp.openById("1xixIOWw2yGd1aX_2HeguZnt8G_UfiFOfG-W6Fk8OSTs"); //This sheet
var srcSht = SpreadsheetApp.getActive();
var sourceMenu = srcSht.getRange('A1');//This is the cell cotaining the dropdown
var menuTest = sourceMenu.getValue();
// Variable for the vars sheet. If it doesn't exist, create it
var varsTest = source.getSheetByName('vars');
if (!varsTest){source.insertSheet('vars');}
var importedA1 = varsTest.getDataRange().getA1Notation();
varsTest.clearContents();
var t1Imp = '=ImportRange("test1_Id", "Stock!A1:F11")';
var varsData = varsTest.getRange('A1');// This is the cell we fill with the importRange formula
varsData.setValue(t1Imp);
var imported = varsTest.getDataRange().getValues();
var newOrder = imported.map(function(item) {
if (item[4] !== NaN){return [[item[0]],[item[4]]];};
if (item[4] === NaN){return [[item[0]],[item[3]]];};}
var orderRange = source.getSheetByName('Sheet1').getRange(10,1,newOrder.length, newOrder[0].length);
orderRange.setValues(newOrder);
Logger.log("\t" + newOrder);
Logger.log(newOrder):
[(timestamp omitted)] items1,order,caramel,6,c&c,2,mint,3,PB,0,,,items2,,caramel,,strawberry,,mint,,PB,
It seems to be skipping the if statements, or I told it that I mean to test the index as NaN, which will obviously never be true.
I also tried replacing 'NaN' with 'undefined'. Same result. I tried finding the item[4].Values, but it gave me an error. I also tried the same logic using filter() instead of map() but it copied the entire data set.
I pull these values onto a new 'vars' sheet in the workbook (to minimize calls to the web service):
test1
reduce them to the first and last columns, then output:
test
The cells in the 'order' column for the second set of items in the 'test' sheet are blank. The values for that order column should be in item[3] of that array, but I can't get the script to identify that that the blank cells are blank.
I am new to Google Apps Script and JS, but I am watching a lot of tuts and learning by doing. If I find a solution, I will post it.
Thank you StackOverflow, I could not have learned as much as I have without this community!
I have a working function that does what I want. In short:
I had to create a duplicate of the order column in a new column, so that all the values would line up. It's not technically a JS answer, but was the simplest and follows good spreadsheet rules.
function rmZeroOrderPS(item){
var source = SpreadsheetApp.openById("<sheetId>"); //This sheet
var varsTest = source.getSheetByName('vars');
var imported = varsTest.getDataRange().getValues();
var i=-1;
while (i <= imported.length){
if(item[8]!= 0) {return [item[0],item[8]]};
i+=1;
};

Inconsistent problems with Google Sheets data mover script

After around two to three hours of digging across many sites, I cobbled together this functioning script to watch an "input" column on a sheet and, using onEdit(), whenever data is put into that column, move the data further down the sheet to the next available cell in that specific row.
function onEdit(e) {
var s = e.source.getActiveSheet();
var sheetName = 'Pricing Chart';
var colToWatch = 5;
var copyFrom = 5;
var nextEmptyCol = colToWatch + 22;
var emptyCellCheck = s.getRange(e.range.rowStart, nextEmptyCol,1,1);
if (s.getName() !== sheetName || e.range.columnStart !== colToWatch) return;
while (emptyCellCheck.isBlank() !== true){
nextEmptyCol++;
var emptyCellCheck = s.getRange(e.range.rowStart, nextEmptyCol,1,1);
}
if (emptyCellCheck.isBlank()){
s.getRange(e.range.rowStart, copyFrom,1,1)
.copyTo(s.getRange(e.range.rowStart, nextEmptyCol,1,1), {contentsOnly: true}),
s.getRange(e.range.rowStart, copyFrom,1,1).clear({contentsOnly: true});
}
}
Specific example:
Into cell E5, type "222". If AA5 is empty, it will copy "222" into AA5, and then clear E5. If AA5 is not empty, it will check AB5, then AC5, etc until it finds an empty cell. On my specific sheet, it then uses all the data from the row and displays various calculations (average, max, etc) so that those data are visible, but all the individual inputs are tucked away behind the scenes. It's been useful for keeping a large list of data on many different variables in a format that's easy to look at and easy to share with others.
Problem is... sometimes it will do as intended at first, find the next available cell, copy the data, and erase the original input cell (e.g. E5). But, sometimes, it will also erase the cell the data was copied TO (e.g. AB5). Roughly once or twice every ten iterations of the script.
So, I was wondering if anyone could have a look at my script and give me tips on optimizing it or just doing things better so the script runs correctly consistently.

Issue with simple Google Scripts and Google Spreadsheets

Update 2: It was a permissions issue. I guess I have to duplicate all my scripts for each spreadsheet? Also I'm updating my code now that I've fixed it.
Update: my code is wrong (I need to drop the second for loop I think) but my question is why the script isn't running on my sheets.
I'm trying to write data to columns in a spreadsheet. Maybe I'm just having permissions issues?
This is my first time using Google scripts and I'm not familiar with JavaScript either. I have a spreadsheet with a lot of data and I successfully removed duplicates as defined by comparing the first two columns--no bugs, no issues, ran successfully first try. Now I'm trying to fill in data on two new, empty columns.
If column 2 is in the format "foo - bar", I want column 3 to be "foo" and col 4 "bar". So I wrote this script:
function parseTypes() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getDataRange().getValues();
var newData = new Array();
for (i in data) {
var row = data[i];
var str = row[2];
var strSplit = str.split(" - ");
row[3] = strSplit[0];
if (strSplit[1] == "" || strSplit[1] == null || row[4] == undefined) {
row[4] = "";
} else {
row[4] = strSplit[1];
}
newData.push(row);
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
I debugged in and the string array strSplit is accurately being set to "foo,bar". My issue is that it's not actually writing the data to my spreadsheet. I don't know if it's my code or if I'm just running the script wrong because I barely know what I'm doing.
JavaScript use 0 based indexes but SpreadsheetApp use 1 based indexes. This means that row[2] returns the value of column C not column B.
You don't have to copy the script. The only thing you need to change is not using the SpreadsheetApp.getActiveSheet, but you have to use the SpreadsheetApp.openByUrl('https://blalaallla').getSheetByName('blalala') method. This way you don't have to copy it. Hope this helps.

Remove a filter with JavaScript for Google Sheets

I can't find what I need in any of the answers listed. I'm looking for something simple - remove any filter on the sheet and then clear the values in a specific column. Below is my script. It runs to completion but does not perform the un-filter code, leaving rows that have been filtered not cleared.
function resetSheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var activecells1 = sheet.getRange('A2:A');
for (var i = 2; i <= 100; i++) {sheet.unhideRow(sheet.getRange("A"+i));}
activecells1.setValue("").setBackgroundRGB(255, 255, 255);
}
Also - if there's a simple line of code that takes me to the bottom of the active cells in A (instead of using A2:A), that would be helpful too so that I don't have to iterate to 500. The code needs to be dynamic enough to run on multiple sheets, though.
Thanks!
I did not find any Google Reference for dealing with filters by script. Guess, it's not possible.
I think, you could just work with entire range without unfiltering it:
var activecells1 = sheet.getRange('A2:A');
activecells1.clear();
All cells will be cleared (formatting and values) from range A2:A

Categories