Google Spreadsheet Script. Only work for one sheet - javascript

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

Related

Google Sheets script – replace blank spaces

I've got a script that's doing some onEdit formatting on a sheet of mine. All the rest is working well, and I wanted to include a line that deletes spaces from number values I'm importing. That last line is not working.
Any ideas what I'm missing here?
function onEdit(e) {
var cell = e.range;
var sh = e.source.getActiveSheet();
if(sh.getName() === "Trading Journal") {
cell.setBackground('#fff');
cell.setFontSize(10)
cell.setFontFamily()
cell.replace(/\s/g, "")
}
}
https://docs.google.com/spreadsheets/d/1rkjO-ITeLdIHq-LLHfHcp6-1j1R0-giS6HGbwYdJ5Ek/edit?usp=sharing
Did a bit of research regarding this, and it seems that .replace() is a string method and therefore may not work with numbers. Reference
But if you only need to remove whitespaces from numbers, here is a simple solution:
function rSpaces() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var cell = ss.getActiveCell();
cell.trimWhitespace();
}
You can assign this on an onEdit trigger and check this documentation for any font modifications you want to add.

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

Automatically protect a cell / range after inputting data in Google Sheets

I have a public spreadsheet, where people can enter their names under the column "Name". Everything in this sheet is protected, except for the cells in the column "Name". Since the spreadsheet is public, I want to avoid a situation where someone can troll and delete all the names that have been inputted. Hence, I'm trying to set up a script using the on edit triggers to protect the cell in this range after anyone has entered their name in a cell. So far I've been manually protecting the cells after a name has been entered.
I've found out that the best way to do this would be to use the on edit trigger. I have used javascript before but as I'm new to google spreadsheet scrips, I can't get my script to run like it's supposed to. The current script is supposed to automatically protect the range on edit, and add a description of when the protection was done.
Sample spreadsheet with the script in it here: https://docs.google.com/spreadsheets/d/18NlVKcaeyOkgqIa6WAuDsu5TSYK37m_vXLmp7p7Q8kc/edit?usp=sharing
function protectOnEdit(event) {
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('Sheet1!A2:A1000');
var timeZone = Session.getScriptTimeZone();
var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
var description = 'Protected on ' + stringDate;
var protection = range.protect().setDescription(description);
// below code taken directly from Google's documentation
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}
Reference: https://developers.google.com/apps-script/reference/spreadsheet/range#protect()
The data range in question is A2:A1000 and currently it -seems- to partially work, however, it protects the WHOLE range after editing a single cell, instead of just protecting the edited cell like it's supposed to.
Are there any steps I'm missing in order for the script to lock the cells individually, instead of the whole range? Any insights are very appreciated!
I have made some corrections:
function protectOnEdit(e) {
var range = e.range;
// Be sure to have edited the sheet "Sheet1"
if (range.getSheet().getName() != "Sheet1") return;
// Be sure to have a single cell as edited range
if (range.getWidth() != 1 || range.getHeight() != 1) return;
// Be sure to have edited cell inside A2:A1000
if (range.getColumn() != 1 || range.getRow() < 2) return;
// Be sure to have non-blank new value
if (!e.value) return;
// Protect this range
var timeZone = Session.getScriptTimeZone();
var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
var description = 'Protected on ' + stringDate;
var protection = range.protect().setDescription(description);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) protection.setDomainEdit(false);
}
At first the script checks several conditions for desired protection. They seem to me to be important for the task. If all of them are TRUE, then protects a single cell. The spreadsheet owner has no restrictions to edit protected cells but other editors have.
Of course, the owner should install a trigger for this function properly to automate the process.

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.

Categories