Google apps script GoogleSheets:是否可以保护一系列单元格,使其只能用脚本进行修改?
嗨,我有一个共享的谷歌表,当按下按钮时,它会输入日期和时间。但是,一旦输入,我不希望用户能够修改日期。我知道我可以保护一系列单元格,但在这种情况下,我仍然需要宏/脚本才能输入时间 这可能吗Google apps script GoogleSheets:是否可以保护一系列单元格,使其只能用脚本进行修改?,google-apps-script,google-sheets,Google Apps Script,Google Sheets,嗨,我有一个共享的谷歌表,当按下按钮时,它会输入日期和时间。但是,一旦输入,我不希望用户能够修改日期。我知道我可以保护一系列单元格,但在这种情况下,我仍然需要宏/脚本才能输入时间 这可能吗 谢谢。我相信你的目标如下 function runWithWorkaround() { var lock = LockService.getDocumentLock(); if (lock.tryLock(10000)) { try { const url =
谢谢。我相信你的目标如下
function runWithWorkaround() {
var lock = LockService.getDocumentLock();
if (lock.tryLock(10000)) {
try {
const url = "https://script.google.com/macros/s/###/exec";
UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}});
} catch(e) {
throw new Error(e);
} finally {
lock.releaseLock();
}
}
// DriveApp.getFiles() // This comment line is used for automatically detecting the scope for using Web Apps.
}
- 有您(电子表格的所有者)和用户
- 用户通过单击按钮运行脚本,脚本将日期值放入单元格。此时,您希望已经保护了用于向用户输入日期值的单元格
- 但是,当用户单击按钮时,您希望将日期值放入受保护的单元格中
- 在您的情况下,可以使用谷歌应用程序脚本
我很困惑,因为脚本是否与单击按钮的人具有相同的权限?
在这种情况下,当脚本将值放入受所有者保护的单元格时,会出现类似的错误,您试图编辑受保护的单元格或对象。如果需要编辑,请联系电子表格所有者以删除保护。
。因此,为了避免此错误,我们认为当脚本作为所有者运行时,将避免此问题
在这个回答中,我想提出一个解决办法。此解决方法如下所示
function runWithWorkaround() {
var lock = LockService.getDocumentLock();
if (lock.tryLock(10000)) {
try {
const url = "https://script.google.com/macros/s/###/exec";
UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}});
} catch(e) {
throw new Error(e);
} finally {
lock.releaseLock();
}
}
// DriveApp.getFiles() // This comment line is used for automatically detecting the scope for using Web Apps.
}
当用户通过单击电子表格上的按钮运行脚本时,它将使用Web应用程序以所有者身份运行脚本。使用此变通方法时,请执行以下流程
用法:
1.准备电子表格。
请创建新的电子表格并创建一个按钮,并将runWithWorkaround
的功能分配给该按钮。并且,请作为唯一所有者的用户保护单元格“A1”。在此示例中,目标单元格为“A1”
2.准备脚本。
请将以下脚本复制并粘贴到Google电子表格的脚本编辑器中。并且,请设置带有按钮的工作表名称
// This function puts a date to cell "A1".
function putValue() {
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1").getRange("A1").setValue(new Date());
}
// This function is for Web Apps.
function doGet() {
putValue();
return ContentService.createTextOutput();
}
// This function is used for testing "without using this workaround.".
function runWithoutWorkaround() {
putValue();
}
// This function is used for testing "with using this workaround.".
function runWithWorkaround() {
const url = "https://script.google.com/macros/s/###/exec"; // <--- Please replace this URL with your Web Apps URL.
UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}});
// DriveApp.getFiles() // This comment line is used for automatically detecting the scope "https://www.googleapis.com/auth/drive.readonly" for using Web Apps.
}