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ž
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.
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:
This could be put into the spreadsheet in any cell except D19 if it refers to D19, such as this:
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)