How to call ISOWEEKNUM from JS using Google Sheets - google-apps-script

I want to call the google sheets function ISOWEEKNUM from JS in a custom function and can't get it working.
Current code is
function customFun(date) {
return ISOWEEKNUM(date);
}
However that just leads to an error:
ReferenceError: ISOWEEKNUM is not defined
How can I get that working and is there a reference how to call standard functions?

I believe your goal as follows.
You want to retrieve the week number using Google Apps Script.
You want to use the function customFun as the custom function.
For this, how about this answer?
Issue and workaround:
Unfortunately, in the current stage, the built-in functions of Spreadsheet cannot be directly used with Google Apps Script. And also, the custom function cannot put the formula. So in this case, it is required to use the workaround. Here, I would like to propose the following 2 workarounds.
Workaround 1:
In this workaround, when =customFun(date) is put to a cell, it is replaced with =ISOWEEKNUM(date) using the OnEdit event trigger.
Sample script:
In order to use this script, please put =customFun(today()) to a cell. By this, the formula of =customFun(date) is replaced with =ISOWEEKNUM(today()) by the OnEdit event trigger.
function customFun(date) {return ""}
function onEdit(e) {
const range = e.range;
const formula = range.getFormula();
const f = formula.match(/=customFun\(([\S\s\w]+)\)/);
if (f.length == 2) {
range.setFormula(`ISOWEEKNUM(${f[1]})`);
}
}
Workaround 2:
In this workaround, when =customFun(today()) is put to a cell, the week number is calculated by Google Apps Script and the result value is put to the cell.
Sample script:
function customFun(date) {
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
}
return date.getWeek();
}
getWeek() is from https://stackoverflow.com/a/7765814/7108653.
References:
Custom Functions in Google Sheets
Simple Triggers

Related

How could I call a custom function within a QUERY formula on Google Sheets?

Would it be something like this?
=query(IMPORTRANGE("https://docs.google.com/spreadsheets/d/fsdgsgsdhdshldhsdhgvs/edit","Reference Info!A2:J"),"select * where Col2 matches '"&fileName()&"'")
Here is the fileName() function:
//Since I'm not sure fileName() will run as the recalculations happen, I've added this one
function onOpen(){
fileName();
}
function fileName() {
return SpreadsheetApp.getActiveSpreadsheet().getName();
}
Thanks for any help!
Your formula is fine, but it doesn't make sense to have
function onOpen(){
fileName();
}
as custom functions are executed when the spreadsheet is opened and when the custom function arguments change.
Related
Refresh data retrieved by a custom function in Google Sheet
get sheet names not work properly or not auto update after use loop to copy to new sheets

Bringing the cell's location rather than it's value

I'm trying to create a custom formula for Google Sheets using Apps Script. The function will return the Hexadecimal background color of the cell (e.g. =getHEX(B1) will return the color of cell B1).
My problem is that I can bring the value of the cell, not the location. If I use quotes in the function it works (=getHEX("B1")) but I wonder how can I avoid using the quotes and still get the value of the cell.
I tried to use the A1Notation function and it supposedly bring the location (B1) but when added to the function I still get the same error (Range not found).
Below is the function as a reference:
function getHEX(cellReference) {
const getCell = SpreadsheetApp.getActiveSheet().getRange(cellReference.toString()).getBackground();
return getCell;
}
Issue:
Unfortunately, there is no straightforward way to do that since =getHEX(B1) would pass directly the value, and not the actual range that is used in google apps script to get the background.
Simple workaround:
You can use ADDRESS, ROW and COLUMN to get the reference as a string in the google sheets side and pass it as an argument in your custom function so it can be used by the getRange(a1Notation) method.
Solutions:
Solution 1:
Google Apps Script:
function getHEX(cellReference) {
const getCell = SpreadsheetApp.getActiveSheet().getRange(cellReference).getBackground();
return getCell;
}
Google Sheets:
=getHEX(ADDRESS(row(E4),column(E4),4))
to get the background color of cell E4. You can also drag down the formula in this way.
Solution 2:
Use the coordinates directly but structure the function to accept two arguments (x and y).
Google Apps Script:
function getHEX(x,y) {
const getCell = SpreadsheetApp.getActiveSheet().getRange(x,y).getBackground();
return getCell;
}
Google Sheets:
=getHEX(row(E4),column(E4))

Using a variable from another script in the same document (apps scripting)

I am trying to access a variable from another script A.gs in script B.gs. they are both in the same document. How could I do this?
I am not sure how I should solve this problem, I am a beginner with apps scripting and I can't find anything on the internet about it.
code.gs:
ui = DocumentApp.getUi();
function onOpen () {
A = prompt('Hello');
}
code2.gs:
function onOpen () {
if (A === "123") {
ui.alert('Hello')
}
}
I want Hello to be output if 123 is entered into the prompt, but when I try to run the code I get the error:
ReferenceError: "A" is not defined. (line 3, file "code2")
In your situation, code.gs and code2.gs are in a project of a container-bound script type of Google Document.
If my understanding is correct, how about this answer? Please think of this as just one of several answers.
Modification points:
In your script, the scripts of code.gs and code2.gs are used as one project at the script editor. So in your script, there are 2 same functions of onOpen() in the project. In this case, only one of them is run. In your case, onOpen() of code2.gs is run and the error of ReferenceError: "A" is not defined. occurs.
Modified script:
If you want to modify your script and you want to work the functions when the Google Document is opened, how about the following modification?
1. Copy and paste the following script to code.gs and code2.gs of the script editor:
code.gs:
var ui = DocumentApp.getUi();
function installedOnOpen () {
A = prompt('Hello'); // or ui.prompt('Hello').getResponseText();
sample(A);
}
code2.gs:
function sample (A) {
if (A === "123") {
ui.alert('Hello')
}
}
Or, if you want to run independently 2 functions, how about the following modification? In this modification, the value is saved using PropertiesService.
code.gs:
var ui = DocumentApp.getUi();
function installedOnOpen () {
A = prompt('Hello'); // or ui.prompt('Hello').getResponseText();
PropertiesService.getScriptProperties().setProperty("key", A);
}
code2.gs:
function sample () {
var A = PropertiesService.getScriptProperties().getProperty("key");
if (A === "123") {
ui.alert('Hello')
}
}
Or, you can also modify as follows. But, in your situation, this might not be required.
function installedOnOpen () {
var ui = DocumentApp.getUi();
var A = ui.prompt('Hello').getResponseText();
if (A === "123") {
ui.alert('Hello');
}
}
2. Install OnOpen event trigger:
In order to run the function of installedOnOpen when the Google Document is opened, please install the OnOpen event trigger to the funciton of installedOnOpen as the installable trigger.
3. Run script:
In your case, there are 2 patterns for running script.
Pattern 1:
Open Google Document.
Pattern 2:
Run installedOnOpen at the script editor.
By above, installedOnOpen is run. And you can see the dialog at Google Document.
Note:
This modification supposes that the function of prompt() returns the value of 123 as the string value.
If you cannot provide the script of prompt(), as a test case, how about modifying from prompt('Hello'); to ui.prompt('Hello').getResponseText();?
References:
Access a variable across multiple script file under a GAS project
Also I think that this thread might be useful for you.
Installable Triggers
If I misunderstood your question and this was not the direction you want, I apologize.
As I can see you define onOpen twice. It does not make sense.
You also don't declare variables and this is reflected in the style of your code. Try declaring the variables and you will realize that your code has no effect.

Google sheets custom function built-in function

I have following custom function in google sheets, I tried to call a built-in function "TEXT" in my custom function but it is not successful. The Google sheets will prompt "unknown" function "TEXT". Is there a solution for this?
function NextMonth(StockTradeDate) {
var DeltaDate;
if (**TEXT**(StockTradeDate,"mmm") = "JAN" ) {
DeltaDate = 30;
}
return DATEVALUE(StockTradeDate) + 31;
}
Google Apps Script has the Utilities library which includes the formatDate method
Utilities.formatDate(date, timeZone, format)
For details see https://developers.google.com/apps-script/reference/utilities/utilities#formatdatedate-timezone-format
It's worth to say that in Google Sheets it's no possible call a built-in function within the script. If a service like Utilities doesn't include the functions that you are looking for, then the alternative is to build your own version, get it borrowed from a library, a open source project or any other place.
I made an attempt to use the spreadsheet function library from Ethercalc and shared about this on my answer to Is there a way to evaluate a formula that is stored in a cell?
Try using javascript date methods (as below) to drive the date and conditionals you need. Could not locate documentation that supports the Sheets built-in function calls from within an apps script function. Javascript is supported.
function NEXTMONTH(StockTradeDate) {
var DeltaDate
if (StockTradeDate.getMonth() === 0 ) { //Jan:0 Feb:1 ... Dec:11 these will need more conditionals.
DeltaDate = 30;
}
var date2 = new Date(StockTradeDate.valueOf()+ DeltaDate*24*60*60*1000)
// valueOf() is millisec time since 1/1/1970
return date2
}
If you need more info regarding the date methods and implementation, w3schools has an efficient reference.

Google Scripts Sheets hide/ unhide

In writing a 'custom function' Google Script for my particular sheet, I simply want to hide a column:
function hideColumn(index) {
// get active spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
// get first sheet
var sheet = ss.getSheets()[0];
sheet.hideColumns(index);
}
This code works fine when I run it from within the Script editor but if I try to run it from inside a cell "=hideColumn(2)", I get the following error:
"You do not have permission to call hideColumns (line 48)."
From the same sheet/ script I'm able to run other custom functions such as:
function metersToMiles(meters) {
if (typeof meters != 'number') {
return null;
}
return meters / 1000 * 0.621371;
}
This seems to be some issue with the hideColumns function being run from inside a sheet? (ie. custom function?)
Your script 'hideColumn' is not a custom function, but a 'normal script'. Also it does not return anything (whereas the second function does). Only custom functions can be entered like formulas in the spreadsheet. See here for more info. My advice would be to create an extra menu-item using an onOpen trigger so you can run the function from the (spreadsheet)menu.
Hope that helps ?