Google Sheets script – replace blank spaces - javascript

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.

Related

Google Apps Script - Defining a Range List with Another Variable

I'm pretty new to this, so I'm not even sure if this is the most efficient way to do this, but I'm trying to save some space in my Google Apps Script by using a cell value to define a Range List.
Here's the code that I have right now:
function myFunction()
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var aItems = s.getRange('F1').getValue();
var aItemList = s.getRangeList([aItems.getValue]);
Logger.log(aItemList);
}
The variable aItems is getting the the value of cell F1 on my sheet, which is 'E2', 'E5' (I also tried removing the single quotes surrounding the cell numbers, but that didn't change the result)
With aItemList I am attempting to create a Range List using the value of aItems to define the range. I get an exception error when I run the script stating that the range is not found.
Ultimately the purpose of the aItemList variable will be to have a variable that is storing a list of cells containing checkboxes that I can alternate between being True and False. On the actual sheet that I plan on using this for, there will be hundreds of checkboxes, so I want to avoid having to list them all out in the script as part of the array. I mention this because I have tried variations of this code that have successfully logged aItemList as the correct string, but do not allow me to set the cells value to true or false using aItemList as a reference.
If someone could let me know if this is even possible or not, I would greatly appreciate it. And/or if there is an even better method of accomplishing this task of storing specific cells into a variable as an array that would also be highly appreciated.
Try this:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getActiveSheet();
var aItems = s.getRange('F1').getValue().split(',');
Logger.log(aItems);
let rgl = ss.getRangeList(aItems);
Logger.log(rgl.getRanges().map(r => r.getA1Notation()));
}

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:

Replace multiple occurrences in String on Google Spreadsheet

So I have a spreadsheet up for the purpose of documenting descriptions of functions found in some python files. TLDR these descriptions are hard to read due to the clutter left over from the files.
So my solution to solve this was:
function onEdit(e) {
const desFix = ['"', '
'];
let activeSheet = e.source.getActiveSheet();
let range = e.range;
const desc = range.getValue();
const rdesc = desc.toString();
for (let i=0; i<desFix.length; i++){
const rep = rdesc.replace(desFix[i]," ");
range.setValue(rep);
}
}
But it only works on the first occurrence when I need it to happen multiple times. Everything I've found and tried to implement/translate over to spreadsheet api breaks. Any idea of what I need to do to make it run multiple times?
I believe your goal as follows.
You want to convert the values of " and
to " " in the active range in the Google Spreadsheet.
You want to run the script using the OnEdit trigger.
Modification points:
In your script, the same rdesc is used by rdesc.replace(desFix[i]," ") in the for loop. By this, only the 1st
at 2nd loop is replaced. I think that this is the reason of your issue.
And, I think that setValue is used in the for loop, the process cost will be high.
In your case, I thought that TextFinder might be suitable.
So in this answer, I would like to suggest to modify your script using TextFinder. When your script is modified using TextFinder it becomes as follows.
Modified script:
function onEdit(e) {
const desFix = ['"', '
'];
desFix.forEach(f => e.range.createTextFinder(f).matchCase(true).replaceAllWith(" "));
}
When you use this, for example, please edit a cell. By this, the script is run by OnEdit trigger and " and
in the value in the cell are replaced to " ".
Note:
When you want to run the script with the script editor, you can also use the following script. When you use the following script, please run myFunction() at the script editor. By this, all cell values in the active sheet are checked.
function myFunction() {
const desFix = ['"', '
'];
const sheet = SpreadsheetApp.getActiveSheet();
desFix.forEach(f => sheet.createTextFinder(f).matchCase(true).replaceAllWith(" "));
}
References:
Class TextFinder
google-apps-scropt
I thought that these links might be useful.

Google Sheets: Add 200 to new rows "after" number format change

I'm continually adding new rows to Google Sheets with numerical values in Column C. I need a script (not a formula!) to do 2 things with those numbers.
Change the number format to remove commas from any numbers
Add 200 to each number
I've got the script for part 1...
function setFormat(){SpreadsheetApp.getActiveSheet().getRange("C2:C").setNumberFormat('##########0');}
But I need help with part 2.
Both scripts need to occur immediately upon creation of the number in Column C.
I can't use formulas for these changes. I need to use scripts.
Thank you!
You can write whole code within onEdit() function
like this:
function onEdit(e){
var range = e.range;
if(range.getColumn() == 3){ //Column C is 3rd column
SpreadsheetApp.getActiveSheet().getRange("C2:C").setNumberFormat('##########0');
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var r = e.source.getActiveRange();
var cell = r.getA1Notation();
var tempval = sheet.getRange(cell).getValue();
var numval = parseFloat(tempval)+200;
sheet.getRange(cell).setValue(numval);
}
}
Hope this will help you.
Thanks.

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

Categories