Google Spreadsheet custom function made of built i

2020-02-06 02:43发布

I have following function in a cell. It reads date from other cell, than calculates age and transforms it in format "3 weeks 5 days"

=INT((TODAY()-D19)/7)&" weeks, "&(TODAY()-D19-(INT((TODAY()-D19)/7)*7))&" days"

It works.

Now I would like to replace this long string into one simple function:

=AGEINWEEKS(D19)

How can I do that?

I already tried to write this script in Script Editor

function ageInWeeks(from_date) {
  return SpreadsheetApp.getActiveSheet().getRange("D16").setFormula('=ROUND((TODAY()-D16)/7)&" weeks, "&(TODAY()-D16-(ROUND((TODAY()-D16)/7)*7))&" days"');
}

But it returns error

error: You do not have permission to call setFormula (line 3, file "Code")

Thank you in advance!

Regards, Tomaž

2条回答
不美不萌又怎样
2楼-- · 2020-02-06 03:15

From the documentation : Custom functions return values, but they cannot set values outside the cells they are in. In most circumstances, a custom function in cell A1 cannot modify cell A5.

If you describe your tipycal use case one could suggest another approach.

查看更多
Anthone
3楼-- · 2020-02-06 03:17

If you are looking to create a custom function to give the same result as your spreadsheet function, you will have to use Google Apps Script in a way that it performs the calculation, rather than attempt to use it to set a formula into the spreadsheet (which as Serge has pointed out, will not work as it is disallowed).

(Also, just to be clear to future readers, Google Apps Script and their custom functions cannot perform calculations using google spreadsheets formulas. They perform calculations in javascript language. On the other hand, the script, via setFormulas can be used to write a spreadsheet formula into a cell, where the spreadsheet formula will then perform a calculation ... but it cannot do this if the script is being used as a custom function (i.e. if it is called within a cell with an = sign) but only if the script is called from another means, such as a menu item or from a trigger, be it a trigger responsing to a spreadsheet edit or a timer.)

So, you can write javascript into the custom function to calculate the weeks,days and such a script could be:

function ageInWeeks(date) {
var mil = new Date() - new Date(date).getTime()
var seconds = (mil / 1000) | 0;
mil -= seconds * 1000;

var minutes = (seconds / 60) | 0;
seconds -= minutes * 60;

var hours = (minutes / 60) | 0;
minutes -= hours * 60;

var days = (hours / 24) | 0;
hours -= days * 24;

var weeks = (days / 7) | 0;
days -= weeks * 7;
return weeks +' wks, ' + days + ' days'

}

This could be put into the spreadsheet in any cell except D19 if it refers to D19, such as this:

=ageInWeeks(D19)

where the cell D19 contains a date in the past.

(Note that the custom function is likely to be slower than your original spreadsheet formula)

查看更多
登录 后发表回答