0

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?

player0
  • 124,011
  • 12
  • 67
  • 124
TomFree
  • 1,091
  • 3
  • 17
  • 31

1 Answers1

1

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

References:

Tanaike
  • 181,128
  • 11
  • 97
  • 165