如何通过Google Apps Script获取Form关联Sheet的URL
解决方案
该需求可以直接通过Google Apps Script内置的Form服务方法实现,不需要额外的复杂遍历或特殊权限申请。
核心判断逻辑依赖两个Form类的内置方法:
getDestinationType():返回当前表单响应存储的目标类型,枚举值FormApp.DestinationType.SPREADSHEET代表响应存储在独立的Google表格中getDestinationId():返回关联存储目标的ID,未关联任何外部存储目标时返回null
补全后的完整可运行代码如下:
function sheetChecker() { const form = FormApp.getActiveForm(); // 判断是否已关联存储响应的电子表格 if ( form.getDestinationType() === FormApp.DestinationType.SPREADSHEET && form.getDestinationId() ) { const linkedSheet = SpreadsheetApp.openById(form.getDestinationId()); return linkedSheet.getUrl(); } else { // 新建表格后需要手动绑定为表单的响应存储目的地,否则下次运行仍会判定为未关联 const ssNew = SpreadsheetApp.create("New Spreadsheet"); form.setDestination(FormApp.DestinationType.SPREADSHEET, ssNew.getId()); return ssNew.getUrl(); } }
注意:原代码框架中仅创建了新表格,未执行绑定操作,会导致重复运行函数时反复创建新表格,上述代码已经补全了绑定逻辑。
内容的提问来源于stack exchange,提问作者Teed Ferguson
相关产品推荐
相关产品推荐

