Google script - newConditionalFormatRule; whenNumberGreaterThanOrEqualTo not accepting cells? - javascript

I'm building a google script but are having trouble with creating the conditional formatting. If I build them in the sheet, there is no issue with setting the range for the conditional format, then set it to "Greater than or equal to" and give it a cell, like =$B$5.
When I build the same thing using the script, it gives me an error that it only accepts numbers and not cells..?
Can anyone help me with this issue? Or is it simply not supported?
// What i want to work, but throws an error, since it doesn't get a number.
formatrules.push(Rule1);
var rule_builder = SpreadsheetApp.newConditionalFormatRule()
.whenNumberGreaterThanOrEqualTo("=$B$9")
.setBackground("#85e085")
.setRanges([currentsheet.getRange("H3:H8")])
.build();
// Something I tried, but it sets it to a static number and not the cell
formatrules.push(Rule1);
var rule_builder = SpreadsheetApp.newConditionalFormatRule()
.whenNumberGreaterThanOrEqualTo(sheet.getRange('B9').getValue())
.setBackground("#85e085")
.setRanges([currentsheet.getRange("H3:H8")])
.build();

Proposed modification
Since you want a dynamic value what about using the .whenFormulaSatisfied(String formula) function?
Here is an example in your application case:
var rule_builder = SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied("=H3:H8>$B$9")
.setBackground("#85e085")
.setRanges([currentsheet.getRange("H3:H8")])
.build();
Reference
whenFormulaSatisfied(formula)

The parameter in the whenNumberGreaterThanOrEqualTo is of type Number, as specified in the API documentation seen here. You're passing in a string reference to a cell. Instead, you'd have to use SpreadsheetApp.getActiveSheet().getRange("B9").getValue(), as you do in your second attempt. The problem you're running into could be resolved by updating that rule every time the spreadsheet is edited (ie create an onEdit trigger for the function that creates this rule).

The current accepted answer should remain accepted. This is just a complementary post regarding OP's comment:
Seems kind of weird to enter the range again
You can define the range once and then use Template literals to incorporate it into the expression:
var rng = "H3:H8";
var rule_builder = SpreadsheetApp.newConditionalFormatRule()
.whenFormulaSatisfied(`=${rng}>$B$9`)
.setBackground("#85e085")
.setRanges([currentsheet.getRange(rng)])
.build();

Related

Google App Script new editor - string property double underlined

Probably a nube question but I have a line of code:
var c = message.substring(i, i + 1);
It works but in the new Google App Script editor, the string property "substring" has a double-underline under it, which seems to suggest that it's wrong, but it actually works!
"Show Fixes" gives me only two options - to ignore the "error" or disable checking, neither of which seems like what I want to do. Any ideas?
I think it is due to how the variable "message" is defined. I did a quick test trying to replicate your scenario and this is what I got:
With warning:
var message = 0
message = '123456789'
var c = message.substr(1, 5);
Without warning:
var message = '0'
message = '123456789'
var c = message.substr(1, 5);
Both cases have the same result without errors. If you provide more code I can check why the warning is appearing.
edit:
As you have said in the comments, your variable is being defined from the range of a SpreadSheet using getValue(), this method returns an object with the value of the cell. If you want to obtain a string you should use getDisplayValue(). You can also use the built-in method toString() to make sure that any variable is converted into a string.
References:
getValue()
getDisplayValue()

Why do I get an Invalid Argument when using the removeLabel function in Google Script

I'd like to remove my user created label called "Add-to-Spendee-2", from a collection of emails. I've pretty much followed Google's removeLabel() Documentation to the dot on this, but I keep getting an "Invalid argument: label" error.
Here's the code:
function removeLabel()
{
var myLabel = GmailApp.getUserLabelByName('test-add-to-spendee-2');
var threads = GmailApp.search("label:test-add-to-spendee-2 AND from:swiggy AND subject:(Your receipt for Swiggy order)");
for (var x in threads)
{
var thread = threads[x]
thread.removeLabel(myLabel)
}
}
Note: If I substitute the removeLabel(myLabel) with any other function like markUnread(), the code works perfectly.
I think your code will work but I think all you need to do is:
var lbl=GmailApp.getUserLabelByName('Q0/Subject/Name');
var threads=GmailApp.search('label:Q0/Subject/Name');//exactly as you created it
lbl.removeFromThreads(threads);
Try using the debugger and make sure that threads is getting an array of GmailThread objects.
This is what the label look like in the Gmail search window:
They changed the slashes to dashes and used lower case and that's not really what the label looks like.
As I said above in my comment:
I just did that recently and I found that the description of the label in the gmail search window did not agree with how I actually created the label. It displayed a label like this q0-subject-name and I had it created as Q0/Subject/Name when I used q0-subject-name I couldn't find the label and when I used Q0/Subject/Name I found it.

Get URL from image via script on Google Sheets - does this code still work?

I am using Google Sheets.
Cell A1:
=image("address.jpg")
This puts the image in a cell. To get the url from Stack Overflow produced this answer.
I created the script, and Google recognised it in autocomplete. The error I am getting is:
TypeError: Cannot call method "match" of null. (line 10).
I ran the regex through a checker, and it does get what I am looking for i.e the address, but the error seems to indicate that it's coming back with nothing.
Does this still work? Has Google changed something?
My work-around is to create two sheets and have §=image in one sheet, while in the second sheet, I remove § and use a standard Google function.
The linked solution is far better, and I'd like to implement that if I could. I cannot post a comment on the original solution's page as I don't have reputation points.
In your situation, "null" is given as an argument. Because the formula cannot be directly retrieved by =getImageUrl(A1). By this, the error of Cannot call method "match" of null. occurs. The formula can be retrieved by getFormula(). This is also mentioned at Eric Koleda's answer. So for example, the script can be modified as follows.
Modified script:
function getImageUrl(range) {
var formula = SpreadsheetApp.getActiveSheet().getRange(range).getFormula(); // Added
var regex = /=image\("(.*)"/i;
var matches = formula.match(regex);
return matches ? matches[1] : null;
}
Note:
If =image("URL") is put in "A1", when you use this like =getImageUrl("A1"). Please enclose A1 by the double quotes. By this, the string of "A1" is given to the function and is used as the range.
Reference:
getFormula()

Get indentation used in specific line in CodeMirror

I am using CodeMirror and I want to provide some simple code transformation capabilities.
What I need though is to know the placed indentation of the line I am on, for instance:
function test() {
var x = 0; //I need to get that this line has 2 spaces.
var y = function() {
return true; //And that this one has 4 spaces -or a tab.
}
}
Is there a standard way of getting this via the CodeMirror API, or any relevant hack to get it?
As CodeMirror mainly works with syntax analysis (tokens etc) I attempted to analyze the line tokens and combine it with the cursor data, but I thought to ask for something more thorough and clear.
A token's state contains the indented property, which provides such information for the token's indentation:
var token = editor.getTokenAt(editor.getCursor());
console.log(token.state.indented);

Passing Dynamic Range:Google Script

I'm trying to write a custom function that will count and return the number of cells that contain information on a singular column. I'm using a range of A(x):Z(x) and I can't seem to dynamically pass these so I can get a user defined range everytime.
Edit: Current Error I'm receiving right now says: Missing ) after argument list. (line 10, file "Number Of Updates")
So far I have this....
function updateNum(row1,col1,row2,col2)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var s = ss.getSheetByName("report status");
var r = s.getActiveRange(row1+col1:row2+col2); <---Line with error
return (range.length-2)/2
}
any suggestions on how I could make this pass the range?
thanks,
Alexander
change the line for:
var r= s.getRange(row1, col1, row2-row1+1, col2-col1+1);
but that won't solve your problems has the line just behind is a non sense. "range" is not declared. I don't see where you want to go exactly. please write some pseudocode.
If what you want is to count the number of cells that got informations in it, just use the spreadsheet native function
counta()
Its not possible with custom functions because they are deterministic. That is, they will return the same result given the same input.
In your case even if you fix the bugs you are still not passing the actual input just its range limits. Thus if the data inside the range changes you still pass the same input limits thus will return the previous cached result.
There are ways arround that like passing an extra parameter that always changes like 'now()'but that has performance problems as it will recalculate constantly.

Categories