首页 > 解决方案 > 使用脚本从 googlesheets 中的数组返回下一个元素

问题描述

我在谷歌表中有一个名字列表。我正在尝试在谷歌应用程序脚本中创建一个函数,将列表中的下一个名称输出到电子表格中的不同单元格。一旦我返回了每个名字,我想回到开始。

我也尝试过使用 for 循环,但是脚本只是循环遍历每个项目,最后我只返回了最后一个项目。

   function returnNextName() {
       var nameList =
       SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My 
       Homeroom").getRange(2, 1, 22).getValues();

       var outputCell = 
       SpreadsheetApp.getActiveSpreadsheet().getSheetByName("My 
       Homeroom").getRange(1, 4);

       var i = 0; 
       i = i + 1;
       i = i%nameList.length;

       var nextName = outputCell.setValue(nameList[i]);
     }

我的目标是每次运行该函数时,我都会获得列表中的下一个名称。但是,我只得到名字。

标签: arraysgoogle-apps-scriptgoogle-sheets

解决方案


每次调用脚本时都会重新定义

       var i = 0; 
       i = i + 1;
       i = i%nameList.length;

所以你的元素nameList[i]总是一样的。

为避免这种情况,您需要按照 TheMaster 的建议使用PropertiesService 。

ScriptProperties允许您将最后一个索引存储在脚本属性中,并在每次使用脚本时检索和修改它。

样本:

    if(PropertiesService.getScriptProperties().getKeys().length==0){ // first time you run the script
       PropertiesService.getScriptProperties().setProperty('i', 0);
      }   
    var i = Number(PropertiesService.getScriptProperties().getProperty('i'))%nameList.length;
    outputCell.setValue(nameList[i][0]);
    i++;
    PropertiesService.getScriptProperties().setProperty('i', i);

推荐阅读