Google Scripts Error: "You do not have permission to call sort"

1.4k views Asked by At

I am trying to run a custom function within Google Sheets. I do not get a compile error but when I try to call the function, I get an #ERROR along with a message,

You do not have permission to call sort

Is there a way to get around this problem? How can I sort a range within a custom function if range.sort is not available?

Here is my code:

function installmentPrice(priceRange, measuringPeriod, lowestDays,     discount) 
{
    measuringPeriod = measuringPeriod || 5;
    lowestDays = lowestDays || 1;
    discount = discount || 1;

    var sheet = SpreadsheetApp.getActiveSpreadsheet();
    var tempRange = sheet.getRange("C3:C9");

    var newRange = tempRange.offset(0,0,measuringPeriod);
    newRange.sort(newRange.getColumn());

    Logger.log(newRange.getValues());

    var lowestSum = 0;
    var installmentPx = 0;

    for (i=0; i<= lowestDays; i++) {
        lowestSum = lowestSum + newRange[i];
    }

    lowestSum = lowestSum/lowestDays;
    installmentPx = discount * lowestSum;
    return installmentPx;

}
1

There are 1 answers

0
Serge insas On

As specified in the documentation :

A custom function cannot affect cells other than those it returns a value to. In other words, a custom function cannot edit arbitrary cells, only the cells it is called from and their adjacent cells. To edit arbitrary cells, use a custom menu to run a function instead.

Your function tries to modify a range different from the origin cell, that explains the error you get on the newRange object