我目前正在 Google 表格中撰寫一個 Google Apps 腳本,以從電子表格串列中讀取資料(電子表格 url 由用戶提供)。但是,在呼叫SpreadsheetApp.openByUrl().
我撰寫了以下代碼來“驗證”網址:
for(int i = 0; i < urls.length; i ) {
let spreadsheet = null
try {
spreadsheet = SpreadsheetApp.openByUrl(urls[i]);
} catch (e) {
continue;
}
// Continue to do other stuff to read data from spreadsheet...
}
但是,這有一個問題,它能夠捕獲前幾個“您無權訪問所請求的檔案”。例外。但是在發生一定數量的例外之后,我會得到一個無法捕獲的永久錯誤,從而一起停止腳本。
有一個更好的方法嗎?
最小的可重現示例:
- 使用不同的谷歌帳戶創建 3 個谷歌表格
- 使用不同的 google 帳戶,創建一個 google sheet 并將以下代碼添加到 Code.gs
function myFunction() {
// Put any 3 real spreadsheet url that you do not have access to
let urls = [
"https://docs.google.com/spreadsheets/d/1gOyEAz0amm4RghpE4B7f26okU3PG3vWZkrfiC-SBlbw/edit#gid=0",
"https://docs.google.com/spreadsheets/d/1Oia7ADu5BmYroUq1SLyDMHTJowrwSXOhCEyNO3nXmMA/edit#gid=0",
"https://docs.google.com/spreadsheets/d/1HE_IXURpBr_FJN--mwLo6k9gih07ZEtDGBqYSk6KgiA/edit#gid=0",
]
urls.forEach(url => {
try {
SpreadsheetApp.openByUrl(url)
} catch (e) {
console.log("Unable to open this spreadsheet")
}
})
}
function onOpen() {
SpreadsheetApp.getUi().createMenu("Test").addItem("myFunction", "myFunction").addToUi()
}
- 在應用程式腳本面板中運行該函式一次并授權應用程式
- 重繪 這個谷歌表
- 等待自定義選單出現,然后按“選單”>“我的功能”
如您所見,該openByUrl()呼叫位于 try catch 塊內,但是當您通過自定義選單運行該函式時,您仍然會收到“錯誤:您無權訪問請求的檔案。”。
執行日志:

uj5u.com熱心網友回復:
根據您的問題,我認為您的情況可能是由于規范或SpreadsheetApp.openByUrl. 如果我的理解是正確的,為了避免這個問題,將檢查檔案是否可以使用的方法放在前面SpreadsheetApp怎么樣?在您的腳本中,如何進行以下修改?
從 :
SpreadsheetApp.openByUrl(url)
到:
var fileId = url.split("/")[5];
var file = DriveApp.getFileById(fileId);
spreadsheet = SpreadsheetApp.open(file);
- 在此修改中,使用
DriveApp.getFileById(fileId).fileId無法使用時,會發生錯誤。但在這種情況下,try-catch 可以正常作業。這樣,問題SpreadsheetApp就不會發生了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/442369.html
