从循环中提取数据时出现问题

Having trouble extracting data from loop

本文关键字:问题 数据 循环 提取      更新时间:2023-09-26

我想提取工作表"info"上一行的数据,并根据"G"列或工作表"data"中的内容将其放入另一个工作簿中。我试图复制的数据有22行5列,第一行是标题。我写了一个循环来循环浏览"信息"表,但我没有得到正确的值。我认为我没有正确设置阵列。谢谢你所能提供的任何帮助。这是代码:

  var infoSheet = sourceSS.getSheetByName('info');
  var infoData = infoSheet.getRange('A2:E22').getValues();
  var newUserInfo = '';
  for (var j=0; j<infoData[0].length; ++j){
    if (location == infoData[0][j]);{
    newUserInfo = infoData[0];
    }
  }

合并文档页面后:

getValues()

返回此范围的矩形网格值。返回一个包含所有值的JavaScript2d数组,按行然后按列进行索引。数组的每个项可以是以下类型之一:布尔值、int、字符串或日期。空单元格将由数组中的空字符串表示。请记住,当范围索引从1,1开始时,JavaScript数组将从0,0开始索引。

这意味着你应该写:

nestedLoop:
for (var j=0; j<infoData.length; j++)//increment after, index 1 === 0
{
   for (var h=0;h<infoData[j].length;h++)
   {
       if (location == infoData[j][h])
       {
           newUserInfo = infoData[j];
           break nestedLoop;//we can break out of both loops now
       }
   }
}

虽然我对全局名称空间中的标签不太确定,但为了安全起见,我会这样写:

newUserInfo = (function()
{
    for (var i=0; i<infoData.length; i++)
    {
        for (var j=0;j<infoData[i].length;j++)
        {
            if (location == infoData[i][j])
            {
                return infoData[i];
            }
        }
    }
    return false;//nothing found...
}());

您的数组是infoData,如下所示:

[
  [ A2, B2, C2, D2, E2 ],      // infoData[0]
  [ A3, B3, C3, D3, E3 ],      // infoData[1]
   ...
  [ A22, B2, C22, D22, E22 ]   // infoData[20]
]

循环将j逐列遍历infoData[0]的元素,查找与location匹配的内容。这看起来很奇怪。通常,我们希望"记录"在行中,像location这样的值出现在特定列中。

如果location确实在A中,或者在数组中的列0中,那么您要查找的循环将是:

var newUserInfo = [];
for (var row=0; row<infoData.length; ++row){
  if (location == infoData[row][0]);{
    // Found matching location; get info for new user
    for (var col=1; col<infoData[row].length; ++col) {
      newUserInfo.push(infoData[row][col]);
    }
    break; // Exit after copying the matching row
  }
}
if (newUserInfo.length > 0) {
  // Now, the newUserInfo array contains the data that was
  // to the RIGHT of the location column.
  destSheet.getRange(destSheet.lastRow()+1,1,1,newUserInfo.length).setValues([newUserInfo]);
}

编辑:已更新代码。。。现在,一旦找到匹配的行并且将其数据复制到newUserData(它被视为一个数组),搜索就会退出。在搜索循环之后,复制的值可以写入目标工作表——在本例中,假设它们作为新行添加到工作表的底部。