首页 > 解决方案 > 使用自定义表单在 Google 工作表上创建弹出式表单

问题描述

我对在 google 表格上创建函数非常陌生,因此在创建从弹出表单返回值的代码方面很困难。我一直在使用 Google Apps Script 中的这段代码:

var ui = SpreadsheetApp.getUi();
var response = ui.prompt('Getting to know you', 'May I know your name?', ui.ButtonSet.YES_NO);

if (response.getSelectedButton() == ui.Button.YES) {
  Logger.log('The user\'s name is %s.', response.getResponseText());
} else if (response.getSelectedButton() == ui.Button.NO) {
  Logger.log('The user didn\'t want to provide a name.');
} else {
  Logger.log('The user clicked the close button in the dialog\'s title bar.');
}

并且想知道是否有办法将 response.getResponseText 返回到单元格。当我使用“logger.log”部分所在的“return”函数时,我不断收到错误消息- “无法从此上下文中调用 SpreadsheetApp.getUi()”

在编辑此脚本时是否有另一种方法,或者我应该以不同的方式解释为用户交互获取弹出表单。

谢谢

标签: google-apps-scriptgoogle-sheets-custom-function

解决方案


自定义函数有限制,不能调用SpreadsheetApp.getUi()

作为替代方案,您可以绘制一个自定义按钮,您可以为其分配一个脚本

在此处输入图像描述

您可以设计脚本,使其将值设置到单击按钮时处于活动状态的单元格中。

样本

function myFunction() {
  var cell = SpreadsheetApp.getCurrentCell();
  var ui = SpreadsheetApp.getUi();
  var response = ui.prompt('Getting to know you', 'May I know your name?', ui.ButtonSet.YES_NO);
  var output;
  if (response.getSelectedButton() == ui.Button.YES) {
    output = 'The user\'s name is '+ response.getResponseText();
  } else if (response.getSelectedButton() == ui.Button.NO) {
    output = 'The user didn\'t want to provide a name.';
  } else {
    output = 'The user clicked the close button in the dialog\'s title bar.';
  }
  cell.setValue(output);
}


推荐阅读