Google Sheet开发需求:整行/列复选框填满时自动播放声音
实现Google Sheet复选框全选自动播放声音功能
步骤1:在表格中添加复选框
选中需要添加复选框的行/列单元格,点击顶部菜单栏的「插入」→「复选框」,完成基础复选框的创建。
步骤2:编写Google Apps Script代码
- 打开Google Sheet,点击顶部菜单栏的「扩展程序」→「Apps 脚本」,进入脚本编辑器。
- 清空默认代码,粘贴以下脚本:
function onEdit(e) { const sheet = e.source.getActiveSheet(); const editedCell = e.range; // 跳过非复选框的编辑操作 if (typeof editedCell.getValue() !== 'boolean') return; const row = editedCell.getRow(); const col = editedCell.getColumn(); // 检查当前行所有复选框是否全选 const rowRange = sheet.getRange(row, 1, 1, sheet.getLastColumn()); const rowValues = rowRange.getValues()[0]; const isRowAllChecked = rowValues.every(cell => cell === true); // 检查当前列所有复选框是否全选 const colRange = sheet.getRange(1, col, sheet.getLastRow(), 1); const colValues = colRange.getValues().flat(); const isColAllChecked = colValues.every(cell => cell === true); // 行或列全选时触发声音播放 if (isRowAllChecked || isColAllChecked) { playSound(); } } function playSound() { // 生成带自动播放音频的临时对话框 const html = ` <audio autoplay> <!-- 可替换为自己的音频链接,需确保文件已设置公开访问权限 --> <source src="https://actions.google.com/sounds/v1/alarms/digital_watch_alarm_long.ogg" type="audio/ogg"> 你的浏览器不支持音频播放。 </audio> <script> // 播放完成后自动关闭对话框 setTimeout(() => google.script.host.close(), 2000); </script> `; SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutput(html), '提示'); }
步骤3:代码自定义说明
onEdit是表格内置的编辑触发器,每次单元格内容变更时自动运行,仅处理复选框的编辑操作,检查对应行/列是否全选。playSound通过弹出临时HTML对话框实现声音播放,你可以替换<source>标签内的音频链接为自己的音频文件(比如上传到Google Drive后获取公开分享链接)。- 代码中的
setTimeout设置了对话框自动关闭的时长(2秒),可根据音频长度调整数值。
步骤4:测试功能
回到Google Sheet,勾选某一行或某一列的所有复选框,会自动弹出小对话框并播放声音,2秒后对话框自动关闭。
内容的提问来源于stack exchange,提问作者Công Tuấn Kiệt Nguyễn
相关产品推荐
相关产品推荐

