【问题标题】:How query/search for information from one Google spreadsheet to another spreadsheet using GAS?如何使用 GAS 从一个 Google 电子表格查询/搜索信息到另一个电子表格?
【发布时间】:2013-11-01 13:21:38
【问题描述】:

我想创建一个 Google Apps 脚本来执行以下操作:当我在电子表格(例如记录销售额的电子表格)中选择一个包含人员姓名的单元格,并使用菜单按钮调用函数,该脚本使用该人的姓名(或他的文档编号)在另一个电子表格中进行搜索(查询),该电子表格存储完整的消费者数据并包含我需要从该消费者那里生成合同或付款收据的所有信息. 使用 Google Apps 脚本从另一个电子表格中的一个电子表格搜索信息的最佳策略是什么? 您是否有一些具有与此类似的实现的脚本示例?提前感谢您的任何帮助/指导!

【问题讨论】:

    标签: google-apps-script google-sheets


    【解决方案1】:

    单元格选择不会触发任何事件,您必须使用菜单项或按钮来调用该函数,或者,如果您的用例可以接受,请编辑单元格以触发 onEdit 事件.

    “搜索部分”实际上非常简单,电子表格本身或另一个电子表格中的数据并不重要,它只会改变您访问数据的方式(getActiveSpreadsheetopenById())。从那里获取所有值并在生成的二维数组中进行搜索。


    根据您的评论进行编辑:这是一个返回找到的单元格范围的代码示例(我们得到 A1 表示法,但我们可以@987654325 @当然也是。)

    function test(){ // to test the find function with an argument, 'any' in this case 
      var result = findItem('any');
      if(result){Logger.log(result.getA1Notation())}else{Logger.log('no luck !')};
    }
    
    function findItem(item){
      var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
      var data = ss.getDataRange().getValues()
      for(var n = 0;n<data.length;++n){
        if(data[n].indexOf(item)>-1){ // this is a "strict" find, ie the value must be the entire search item. If you want to do partial match you should compare differently...
          return (ss.getRange(n+1,data[n].indexOf(item)+1)); // if found return the range. note the +1 because sheets have 1 index while arrays have 0 index
        }
      }
      return false;// if we come to the end of sheet without result...
    }
    

    【讨论】:

    • 嗨,Serge,再次感谢您提供更多的 awnswer。你能告诉我如何实现这个“对结果二维数组进行搜索”吗?最好的方法是什么?一个for循环迭代和比较字符串? (查询字符串和名称字段字符串?)
    • 没错,是的。您可以利用数组函数使用 indexOf() 方法在每一行中查找匹配项,但主循环将是一个用于迭代行的 for 循环。
    • 答案已更新为示例代码。在此示例中,我阅读了相同的电子表格,但正如我所说,这只是如何打开 SS...
    • 现在回答你的问题了吗?或者您想了解更多详情?
    • 谢谢,它回答了!
    猜你喜欢
    • 2017-10-12
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2013-07-03
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多