【问题标题】:How find a specific column index based on a cell value如何根据单元格值查找特定的列索引
【发布时间】:2018-07-28 13:58:12
【问题描述】:

在 Google 表格中,我在一个电子表格文件中有两张名为 STUDENTS 和 CLASSES 的表格。它们中的每一个在某些列标题下都包含很多行数据。

STUDENTS 的列标题是 CLASSES 的列标题的子集。

我希望我的 G.A.S 代码识别 STUDENTS 中的活动单元格,然后识别该活动单元格的列标题,然后在 CLASSES 的列标题中找到该列标题,最后返回该标题的列索引课程。

这是我写的代码:

  var spreadsheet = SpreadsheetApp.getActive();
  var sheet = spreadsheet.getSheetByName('Students');
  var targetSheet = spreadsheet.getSheetByName('Classes');
  var sheetColumnIndex = sheet.getActiveCell().getColumnIndex();
  var sheetColumnHeader = sheet.getRange(1,sheetColumnIndex).getValues();

  var numRows = 1 // The column headers of CLASSES are available in 1 row
  var numColumns = 22 // The number of column headers in CLASSES;

  var searchRange = targetSheet.getRange(1,1,numRows, numColumns);
  // get the values in an array
  var values = searchRange.getValues();
  // examine the values in the array

  for (var y = 0; y < values.length; y++) {
     if(values[0][y] == sheetColumnHeader){

       var columnIndexInSourceSheet = y + 1;

     };
  };

  return columnIndexInSourceSheet;

};

但不幸的是,代码不起作用!我不知道为什么!

【问题讨论】:

  • edit 您的帖子以包含新代码。
  • 关于sheetColumnHeader,@Anton Dementiev 提到过。而且,在你的脚本中,columnIndexInSourceSheet 不能被范围返回。例如,请在 for 循环之前声明 var columnIndexInSourceSheet。届时,请删除varvar columnIndexInSourceSheet = y + 1;

标签: google-apps-script google-sheets find


【解决方案1】:

它不起作用,因为您将字符串与数组进行比较。 'getValues()' 方法返回值的二维数组。例如,如果标题是'name',它将返回

var values = range.getValues();
Logger.log(values); //[["name"]]

sheetColumnHeader 变量使用“getValue()”方法。

【讨论】:

  • 感谢您的回答。我按照你说的修改了代码,但是没用。还是不行。代码始终将变量 y 返回为 1,并且变量 columnIndexInSourceSheet 始终未定义!!
  • 您应该提供有关您的工作和预期结果的更多信息。 Stack Overflow 用于询问特定的编程相关问题。这里没有人会逐行调试您的代码。此外,“它不起作用”并不是一个真正的答案。错误信息必须全面
猜你喜欢
  • 2012-11-11
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 2011-07-04
  • 2023-03-13
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
相关资源
最近更新 更多