Google appscript表单显示供用户选择的数组值

google appscript form presenting array values for user selection

本文关键字:选择 数组 用户 appscript 表单 显示 Google      更新时间:2023-09-26

我不确定如何编写GAS表单按钮来触发具有动态值的脚本。在此场景中,当前工作表单元格值用于查找相邻工作表中的行并填充结果数组。然后,表单显示一个按钮列表,其中包含来自结果数组的一列的值。按下表单按钮应该触发postLocationData脚本,用结果数组值更新行中当前单元格和相邻单元格,并关闭表单。此时,按下表单按钮似乎没有任何作用。非常感谢你的帮助:)

function lookUpLocationTest(){
  var ui = SpreadsheetApp.getUi();
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var cell = sheet.getActiveCell();
  var sheetLocations = ss.getSheetByName('LU_Locations');
  var arrayRecords = sheetLocations.getRange(2, 3, sheetLocations.getLastRow(), 2).getValues();

  var matchingLocations=[];
  for (var i=0;i<arrayRecords.length;i++) {
    var result = arrayRecords[i][1].indexOf(cell.getValue())
    if(result !== -1) { 
      matchingLocations.push(arrayRecords[i]);
    }
  }
  if(matchingLocations.length === 0){
    var result = ui.alert(
      'Message:',
      'No Matching Location Found.',
      ui.ButtonSet.OK);
    return 0;
  }      
  Logger.log(' Process - ' + matchingLocations.length + ' Locations have been found.') ; //matchingLocations is a global
  // Prep Form HTML with formatted matching Locations  
  var HTML= '<form><div>'
  for(var i=0;i<matchingLocations.length;i++){
    HTML += "<div><input type='button' value='" + matchingLocations[i][1] 
    + "' onclick='google.script.run.withSuccessHandler(postLocationData).processForm(this.parentNode)'/></div>";
  }
  var htmlOutput = HtmlService.createHtmlOutput(HTML).setSandboxMode(HtmlService.SandboxMode.IFRAME);
  var result = SpreadsheetApp.getUi().showModalDialog(htmlOutput, 'Matching Locations');
  return 1;
}
function postLocationData(lookUpValue) {
  var location = lookUpValuesInArray (matchingLocations, 1, lookUpValue);  //matchingLocations is a global
  var cell = currCell;
  var latLongCol = 3;
  cell.setValue(location[0][1]);
  cell.getRowIndex();
  var sheet = cell.getSheet();
  sheet.getRange(cell.getRowIndex(), latLongCol).setValue(location[0][0]);
  var temp =1;
}

函数" google.script.run "将在客户端执行,但它将调用服务器端(您的.gs文件)上的函数。在这种情况下,您将调用的函数是"processForm()",其中您正在发送"this"。

在你的app脚本文件(gs文件)中,你应该有一个名为"processForm()"的函数,你没有在示例中发布它。

此函数结束后,如果一切顺利,函数"google.script.run"将执行您在"withSuccessHandler()"中定义的函数。在您的示例中,您使用了"postLocationData"。

这个函数将接收执行processForm()返回的结果作为参数。

正如我之前提到的,google.script.run是在客户端调用的,因此,如果一切顺利,将执行的函数(包含在withSuccessHandler中的函数)也必须在客户端。这意味着它必须是HTML中包含的脚本的一部分。

作为你发布代码的方式,我将更改onclick为:

onclick='google.script.run.withSuccessHandler(someJavascriptFunction).postLocationData(this.parentNode)

withSuccessHandler是可选的,如果你决定使用它,那么你应该在你的html变量中创建一个html script标签,让javascript函数显示一个警告或告诉用户点击按钮的结果。

你也可以在appsscript项目中创建一个html文件,并命名为:HtmlService.createHtmlOutputFromFile('Index').setSandboxMode(HtmlService.SandboxMode.IFRAME);

这样你可以有一个更干净的html文件和与之关联的javascript。