Issue with simple Google Scripts and Google Spreadsheets - javascript

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.

Related

Exception: Range not found. Trying to place multiple columns using an active cell. (however works when manually entered)

I'm trying to insert values into cells. Here is my code:
var values = [
["test1", "test2", "test3"]
];
var ss = SpreadsheetApp.getActiveSpreadsheet()
// var sheet = ss.getSheets()[0]
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet()
var cellsToWriteTo = []
function testFunction() {
var activeCell = sheet.getActiveCell();
var firstRow = activeCell.getRow()
var firstColumn = activeCell.getColumn()
cellsToWriteTo = `["R${firstRow}C${firstColumn}:R${firstRow}C${firstColumn + 2}"]`
console.log(cellsToWriteTo)
var range = sheet.getRange(cellsToWriteTo)
range.setValues(values);
}
This gives me the error:
Exception: Range not found
However if I copy and paste cellsToWriteTo from the console log and put it into getRange.. it works perfectly every time..
Things i have tried so far:
Thought it was to do with not fetching the spreadsheet correctly (getActiveSpreadsheet().getActiveSheet()).
Fixed how my values were organised (into arrays within arrays)
Googled the error message and looked at how to properly getRange/setRange in the documentation and in tutorials. Apparently you cannot set arbitrary cells if you are calling them from the excel sheet itself. This is my suspicion as to what is going wrong here. However how can this be the case if when I put in a simple string it functions fine. I am simply doing string interpolation here.
I know this is rudimentary stuff, any help would be appreciated.
Removing both brackets and quotation marks should make it work
Modification:
cellsToWriteTo = `R${firstRow}C${firstColumn}:R${firstRow}C${firstColumn + 2}`
Execution:
Output:

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

Concatenate tables in one and insert it in Google Spreesheet

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

Google Spreadsheet Script. Only work for one sheet

I have this code that I found online and it works as needed, but it works for all my sheets or the tabs at the bottom if you want to call them. I want it to work
function onEdit(event)
{
var sheet = event.source.getActiveSheet();
var eventRange = event.source.getActiveRange();
var eventColumn = eventRange.getLastColumn();
if (eventColumn == 1)
{
var stampRange = eventRange.offset(0,10);
stampRange.setValue(new Date());
}
}
This is the original code, I tried adding in line 4 the following but i can't get it to work. I'm not experienced with javascript but I need your help as i'm trying my best. Thank you.
if(sheet.match(/*.13/)){
This is the line I added. Based on my reading online, the script should works only if the sheet name ends with 13. But it's not working.
You've got the right idea, but sheet is a Sheet Object, while .match() is a String method. Use the Sheet.getSheetName() method to get the name of the sheet (the words on the tab).
In an onEdit(), you usually want to bail out without investing much processing time, so you should put the test for the sheet name as early as possible.
If you want to match "Sheet13" exactly, you should test for just that - because your regex will also match "Apollo13" and "a13a", for example.
function onEdit(event)
{
var sheetName = event.source.getActiveSheet().getSheetName();
if (sheetName.match(/.13/) == null)
// These aren't the droids you're looking for...
return;
var eventRange = event.source.getActiveRange();
var eventColumn = eventRange.getLastColumn();
if (eventColumn == 1)
{
var stampRange = eventRange.offset(0,10);
stampRange.setValue(new Date());
}
}

Google script method getLastRow getting null

function getInfo(){
var id = "xyz";
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
for (var i = 2; i < (lastRow + 1); i++){
var Emails = sheet.getRange(i, getColIndexByName("Email")).getValue();
var row = Compare(Emails, id);
if(row)
PlusFreq(row, id);
else if (checkEmail(Emails))
setEmail(Emails, id);
}
}
My code is working fine , but the method getLastRow();
isn't working it's getting null, Why that is happening?
A week ago it was working properly but now does not it, besides I use the method en getLastRow other functions and also was not this working anymore.
You might want to take a look at the following line in the documentation:
method getLastRow()
Returns the position of the last row that has content.
You may have to check that the sheet contains at least one row with content before you call the getLastRow() function.
I managed to fix the error but do not know what it caused it, simply deleted the blank lines that existed after the 60 lines of content, and added them again, so stopped the error, I'm sure the lines estavao blank. error crazy

Categories