遍历范围以查找匹配的字符串谷歌脚本



我正在尝试遍历电子表格的顶部标题行,以根据标题名称查找列的索引号,这样如果有人插入列,我的代码就不会中断。这是我到目前为止所拥有的:

var sheet = SpreadsheetApp.getActive().getSheetByName('RawData');
var values = sheet.getRange(1,1,sheet.getMaxRows(),sheet.getMaxColumns()).getValue(); //line that's breaking
range.setNote("inside function");
var i = 1;
while(values[1][i] != name) {
i++;
}return i;
}

代码似乎在我设置"值"的行上中断,我不知道如何访问我创建的数组以检查哪个数组包含与"name"参数相同的字符串。setNote 行仅用于测试目的,您可以忽略它。 提前谢谢。

编辑

function getColumnByName() {
var name = "Ready For Testing?";
var ss=SpreadsheetApp.getActive().getSheetByName('RawData');
var vA=ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn()).getValues();
var hA=vA.shift();//returns header array vA still contains the data
var idx={};
var index = hA.forEach(function(name,i){idx[name]=i});//idx['header name'] returns index  
return index;
}

我设置名称只是为了测试目的,当我使用实际函数时,它将作为参数传递

尝试

function getColumnByName() {
var name = "Ready For Testing?";
var ss=SpreadsheetApp.getActive().getSheetByName('RawData');
var vA=ss.getDataRange().getValues();
var hA=vA.shift();//returns header array vA still contains the data
var idx= hA.indexOf(name);
if(idx === -1 ) throw new Error('Name ' + name + ' was not found');
return idx + 1; // Returns the name position 
}

而不是

var values = sheet.getRange(1,1,sheet.getMaxRows(),sheet.getMaxColumns()).getValue();

而不是

var vA=ss.getRange(1,1,ss.getLastRow(),ss.getLastColumn()).getValues();

var values = sheet.getDataRange().getValues();
  1. getValue()仅返回左上角单元格的值
  2. 使用sheet.getMaxRows()/sheet.getMaxColumns()返回工作表的最后一行/列,这可能会导致获得大量空白行/列。
  3. 与第二行代码(getLastRow()/getLastColumn()(相比,建议的代码行"更便宜"(一次调用电子表格服务而不是三次(1.getRange, 2.getLastRow, 3getLastColumnVs.getDataRange(来获取数据范围,通常也更快。

关于

var index = hA.forEach(function(name,i){idx[name]=i});

forEach返回undefinedref. Array.prototype.forEach

试试这个:

function myFunction() {
var ss=SpreadsheetApp.getActive()
var sh=ss.getSheetByName('RawData');
var vA=sh.getRange(1,1,sh.getLastRow(),sh.getLastColumn()).getValues();
var hA=vA.shift();//returns header array vA still contains the data
var idx={};
hA.forEach(function(h,i){idx[h]=i});//idx['header name'] returns index  
var end="is near";//set a break point here and run it down to here in the debugger and you can see hA and idx
}

hA 是标头名称数组

idx 是一个返回给定标头名称索引的对象

idx 是你所需要的,你只需要学习将来将这三行代码放在你的脚本中,你不需要使用外部函数调用来获取索引。

var hA=vA.shift();//returns header array vA still contains the data
var idx={};
hA.forEach(function(h,i){idx[h]=i});//idx['header name'] returns index  
vA still contains all of your data