问题
I am still trying to wrap my head around using script, so my apologies if this is basic.
I have a summary Spreadsheet that pulls values from hundreds of other documents. This used (too many) importrange formulas, but many of these are now #REF or ...Loading.
I am trying to create a custom formula that will mimic the importrange function and return the values. I thought the hard part would be getting the formulas to update when another document was updated, but I have fallen right at the start.
This is my code.
function GetRngValue(ShtURL, GetRng) {
// find id from shtURL? - check if the workbook was updated in the last minute
Logger.log(ShtURL);
var Source = SpreadsheetApp.openByUrl(ShtURL);
// IF Source lastupdated > ThisSht lastupdated then [ Ensure update runs at startup though ]
if (DriveApp.getFileById(Source.getId()).getLastUpdated() > DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).getLastUpdated()) {
var shtNm = GetRng.substring(1,find("!")-1);
Logger.log(shtNm);
var myRng = GetRng.substring(find("!")+1,len(GetRng));
Logger.log(myRng);
TargetRng = Source.getSheetByName(shtNm)
var TargetRng = Source.getSheetByName(shtNm).getRange("'"+myRng+"'").getValues;
Logger.log(TargetRng);
return TargetRng;
};
Logger.log("First - "+DriveApp.getFileById(Source.getId()).getLastUpdated()+" meets last - "+DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId()).getLastUpdated());
Logger.log("Ending");
}
I am getting the error: Exception: You do not have permission to call SpreadsheetApp.openByUrl. Required permissions: https://www.googleapis.com/auth/spreadsheets (line 4).
The formula in the cell is: =GetRngValue("""https://docs.google.com/spreadsheets/d/1axNelBTg4j..etc..7xJx2lSk/edit""", """Summary!B32""") Can anyone point me in the right direction? Can I not reference another GSheet from a custom formula?
回答1:
As mentioned by TheMaster, you're better off without custom functions here. They place a lot more restrictions and are slower than if your spreadsheet were updated via script–replacing your IMPORTRANGE()
functions with GetRngValue()
wouldn't help you much if it were even possible. If you're pulling "values from hundreds of other documents", then it's likely you're well due for an overhaul anyway.
In the documentation for custom functions, it's stated that "custom functions never ask users to authorize access to personal data". This includes spreadsheet data and is later made more explicit:
Cannot open other spreadsheets (SpreadsheetApp.openById() or SpreadsheetApp.openByUrl()).
来源:https://stackoverflow.com/questions/63907877/custom-formula-to-look-at-a-different-gsheet