如何获取绑定Google Sheets的所有Google Forms ID及校验指定ID
解决方案
原有代码问题说明
你使用的代码存在两个问题:
- 语法错误:
SpreadSheetApp拼写大小写错误(正确写法为SpreadsheetApp),且末尾多了多余的右括号,实际运行会触发语法报错 - 功能限制:
SpreadsheetApp.getActiveSpreadsheet().getFormUrl()方法仅返回最早绑定到当前表格的单个表单的URL,因此只能获取到一个表单ID
获取所有绑定表单的ID
Google Sheets中每个关联的表单都会对应一个独立的响应存储sheet,因此遍历所有sheet检查关联表单即可拿到全部ID,示例代码如下:
function getAllLinkedFormIds() { // 取当前激活的表格 const activeSs = SpreadsheetApp.getActiveSpreadsheet(); const allSheets = activeSs.getSheets(); const linkedFormIds = []; allSheets.forEach(sheet => { const formUrl = sheet.getFormUrl(); // 仅当前sheet关联了表单才处理 if (formUrl) { const currentFormId = FormApp.openByUrl(formUrl).getId(); linkedFormIds.push(currentFormId); } }) // 控制台打印所有获取到的表单ID console.log("所有关联表单ID:", linkedFormIds); return linkedFormIds; }
校验表单ID是否匹配预期
将你预设的表单ID存入数组,和实际获取到的ID数组做比对即可完成校验,示例代码如下:
function checkFormIdsMatch() { // 填入你预期的两个表单ID const expectedIds = ["替换为你的第一个预期表单ID", "替换为你的第二个预期表单ID"]; const actualIds = getAllLinkedFormIds(); // 不要求顺序的全匹配校验 const allMatch = expectedIds.every(id => actualIds.includes(id)) && actualIds.every(id => expectedIds.includes(id)); if (allMatch) { console.log("校验通过:所有关联表单ID和预期一致"); return true; } else { const missingIds = expectedIds.filter(id => !actualIds.includes(id)); const unexpectedIds = actualIds.filter(id => !expectedIds.includes(id)); console.log("校验不通过"); if (missingIds.length) console.log("缺失的预期ID:", missingIds); if (unexpectedIds.length) console.log("未预期的关联表单ID:", unexpectedIds); return false; } }
如果需要要求ID顺序也匹配,把上面的校验逻辑替换为逐项比对即可。
内容的提问来源于stack exchange,提问作者ads adsf
相关产品推荐
相关产品推荐

