简体   繁体   English

Google Sheets 脚本 - 对于范围 1 中的每个使用过的单元格,如果单元格值存在于范围 2 中,则获取范围 2 匹配的行号

[英]Google Sheets script - For each used cell in range 1, if cell value exists in range 2, get range 2 match's row number

I feel I have this script almost working as intended, but I am unsure as to where to place certain components of the procedure within the for loop to achieve the desired result.我觉得我的这个脚本几乎按预期工作,但我不确定在 for 循环中放置过程的某些组件以达到预期结果的位置。 Tunnel vision is very much in effect right now, it's entirely possible I am overthinking a simple task.隧道愿景现在非常有效,我完全有可能对一个简单的任务想得太多。 Please let me know if I can describe the issue more clearly.如果我能更清楚地描述这个问题,请告诉我。 Any suggestions or pointers towards an existing resource are helpful.对现有资源的任何建议或指示都是有帮助的。

Setup: Sheet one contains a dynamic vertical list of text values starting in cell I3 going down.设置:第一个表包含从单元格 I3 开始向下的动态垂直文本值列表。 Sheet two contains a dynamic vertical list of text values starting in range A2 going down, and has a similar set of text values in the same rows in column B.第二张表包含从 A2 范围开始向下的文本值的动态垂直列表,并且在 B 列的相同行中有一组类似的文本值。

Goal:目标:

  • Get the value of each used cell in Sheet1 column I (range one)获取 Sheet1 列 I 中每个使用过的单元格的值(范围一)
  • Get the value of each used cell in Sheet2 column A (range two)获取 Sheet2 A 列中每个使用过的单元格的值(范围二)
  • For each used cell in range one, check the value of each range one cell to see if the value exists in range two对于范围一中的每个使用过的单元格,检查每个范围一单元格的值,以查看该值是否存在于范围二中
  • If a match exists, get the row number of the cell in range two that contains the value (there will only ever be a single match if a match exists)如果存在匹配项,则获取包含该值的范围二中单元格的行号(如果存在匹配项,则只会有一个匹配项)
  • Get the value of the cell on that same row in Sheet2 column B获取 Sheet2 列 B 中同一行单元格的值
  • Set the above value as the cell value in the row containing the value found in both ranges on Sheet1 Column M将上述值设置为包含在 Sheet1 列 M 上的两个范围中找到的值的行中的单元格值

Below is what I have been able to come up with.下面是我已经能够想出的。 I am able to get it to function up to the last step.我能够让它运行到最后一步。 It seems the matching rowNumber variable is not updating with each for loop.似乎匹配的 rowNumber 变量没有随着每个 for 循环而更新。

// Get values of range one
var lastRowRangeOne = sheetone.getRange('I3').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
var rangeOneValues = sheetone.getRange('I3:I' + lastRowClientColumn).getValues();

// Get values of range two
var sheettwo = spreadsheet.getSheetByName('Sheet2');
var sheettwoLastRow = sheettwo.getLastRow();
var sheettwoList = sheettwo.getRange('A2:A' + sheettwoLastRow).getValues();
var sheettwoListFlat = sheettwoList.map(function(row) {return row[0];});

    for (var i = 0; i< rangeOneValues.length ; i++){ // for each row in range one
    
      if (sheettwoListFlat[i] == rangeOneValues[i]) { // if the range one value exists in range two

        var rowNumber = sheettwoListFlat.indexOf(rangeOneValues[i]) + 3; // get the row number of the matching value found in range two
        var sheetOneColumnMValue = sheettwo.getRange('B' + rowNumber).getValue(); // get the cell value of the same row in sheet two column B
        var sheetOneRowNumber = i + 3; // get the row number of the range one value
        sheetone.getRange('M' + sheetOneRowNumber).setValue(sheetOneColumnMValue); // set the cell value of sheet one column M row x, where x is sheetOneRowNumber
      }

    }
function compareTwoCols() {
  const c1 = 'COL1';//column names
  const c2 = 'COL3';
  const ss1 = SpreadsheetApp.openById(gobj.globals.datagenid);//data set 1
  const sh1 = ss1.getSheetByName('Sheet1');
  const [hd1, ...vs1] = sh1.getDataRange().getValues();
  let col1 = {};
  hd1.forEach((h, i) => { col1[h] = i });
  const ds1 = vs1.map((r, i) => {
    return r[col1[c1]];
  });
  const ss2 = SpreadsheetApp.openById(gobj.globals.ssid);//data set 2
  const sh2 = ss2.getSheetByName('Sheet0');
  const [hd2, ...vs2] = sh2.getDataRange().getValues();
  let col2 = {};
  hd2.forEach((h, i) => { col2[h] = i });
  const ds2 = vs2.map((r, i) => {
    return r[col2[c2]]
  });
  let matches = { pA: [] };
  let idx = -1;
  ds1.forEach((e, i) => {
    let from = '';
    do {
      idx = ds2.indexOf(e, from);
      if (~idx) {
        if (!matches.hasOwnProperty(e)) {
          matches[e] = [];
          matches[e].push({ val1: e, row1: i + 2, col1: col1[c1] + 1, row2: idx + 2, col2: col2[c2] +1 });
          matches.pA.push(e);
        } else {
          matches[e].push({ val1: e, row1: i + 2, col1: col1[c1] + 1, row2: idx + 2, col2: col2[c2] + 1});
        }
        from = idx + 1;
      }
    } while (~idx);
  });
  Logger.log(JSON.stringify(matches));
}

Spreadsheet1 Sheet1:电子表格 1 表格 1:

COL1 COL1 COL2 COL2 COL3 COL3 COL4 COL4 COL5 COL5
3 3 4 4 2 2 3 3 4 4
2 2 6 6 6 6 1 1 4 4
5 5 1 1 7 7 5 5 5 5
9 9 8 8 7 7 9 9 5 5
7 7 9 9 0 0 8 8 1 1
8 8 2 2 8 8 7 7 9 9
5 5 8 8 7 7 9 9 9 9
1 1 2 2 0 0 8 8 6 6
2 2 7 7 4 4 0 0 3 3
8 8 2 2 0 0 2 2 6 6

Spreadsheet2 Sheet0:电子表格2 Sheet0:

COL1 COL1 COL2 COL2 COL3 COL3 COL4 COL4 COL5 COL5
5 5 1 1 2 2 7 7 6 6
4 4 5 5 7 7 8 8 2 2
6 6 3 3 8 8 1 1 5 5
0 0 7 7 6 6 3 3 6 6
4 4 7 7 6 6 1 1 7 7
5 5 6 6 9 9 2 2 1 1
3 3 0 0 2 2 2 2 8 8
4 4 5 5 0 0 8 8 1 1
1 1 3 3 9 9 2 2 2 2
3 3 6 6 7 7 0 0 3 3

Matches Object:匹配对象:

{
   "2":[
      {
         "val1":2,
         "row1":3,//ds1 row 3
         "col1":1,
         "row2":2,//ds2 row 4
         "col2":3
      },
      {
         "val1":2, 
         "row1":3,//ds1 row 3
         "col1":1,
         "row2":8,//ds2 row 8
         "col2":3
      },
      {
         "val1":2,
         "row1":10,
         "col1":1,
         "row2":2,
         "col2":3
      },
      {
         "val1":2,
         "row1":10,
         "col1":1,
         "row2":8,
         "col2":3
      }
   ],
   "7":[
      {
         "val1":7,
         "row1":6,
         "col1":1,
         "row2":3,
         "col2":3
      },
      {
         "val1":7,
         "row1":6,
         "col1":1,
         "row2":11,
         "col2":3
      }
   ],
   "8":[
      {
         "val1":8,
         "row1":7,
         "col1":1,
         "row2":4,
         "col2":3
      },
      {
         "val1":8,
         "row1":11,
         "col1":1,
         "row2":4,
         "col2":3
      }
   ],
   "9":[
      {
         "val1":9,
         "row1":5,
         "col1":1,
         "row2":7,
         "col2":3
      },
      {
         "val1":9,
         "row1":5,
         "col1":1,
         "row2":10,
         "col2":3
      }
   ],
   "pA":[//just an array of all of the matches
      2,
      9,
      7,
      8
   ]
}

If you print the value of sheettwoListFlat , it has only 5 elements.如果打印sheettwoListFlat的值,它只有 5 个元素。 Once the iterator of for loop reaches 5 or more it will automatically set if (sheettwoListFlat[i] == rangeOneValues[i]) { to false.一旦 for 循环的迭代器达到 5 个或更多,它将自动设置if (sheettwoListFlat[i] == rangeOneValues[i]) {为 false。 Also the statement will only work if the elements of the same index of both arrays are equal.此外,该语句仅在两个数组的相同索引的元素相等时才有效。

It would be also more efficient if you search the Sheet1 using the values of Sheet2 since Sheet2 has lesser value.如果使用Sheet2的值搜索Sheet1也会更有效,因为Sheet2的值较小。

Here I used TextFinder to find the text within a range.在这里,我使用TextFinder来查找范围内的文本。

Using Sheet2 values as search key使用 Sheet2 值作为搜索键

Code:代码:

function myFunction() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheetone = spreadsheet.getSheetByName('Sheet1');

  var lastRowRangeOne = sheetone.getRange('I2').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
  var rangeOneValues = sheetone.getRange('I2:I' + lastRowRangeOne);
  var sheettwo = spreadsheet.getSheetByName('Sheet2');
  var sheettwoLastRow = sheettwo.getLastRow();
  var sheettwoList = sheettwo.getRange('A2:B' + sheettwoLastRow).getValues();

  for (var i = 0; i < sheettwoList.length; i++){
    var find = rangeOneValues.createTextFinder(sheettwoList[i][0]).findNext()
    if(find){
      var sheetOneRowNumber = find.getRow();
      sheetone.getRange('M' + sheetOneRowNumber).setValue(sheettwoList[i][1]);
    }
  }
}

Using Sheet1 values as search key使用 Sheet1 值作为搜索键

Code:代码:

function myFunction() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheetone = spreadsheet.getSheetByName('Sheet1');

  var lastRowRangeOne = sheetone.getRange('I2').getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow();
  var rangeOneValues = sheetone.getRange('I2:I' + lastRowRangeOne).getValues();
  var sheettwo = spreadsheet.getSheetByName('Sheet2');
  var sheettwoLastRow = sheettwo.getLastRow();
  var sheettwoList = sheettwo.getRange('A2:B' + sheettwoLastRow);

  for (var i = 0; i< rangeOneValues.length ; i++){ // for each row in range one
    var find = sheettwoList.createTextFinder(rangeOneValues[i][0]).findNext();
    if(find){
      var rowNumber = find.getRow()
      var sheetOneColumnMValue = sheettwo.getRange('B' + rowNumber).getValue(); // get the cell value of the same row in sheet two column B
      var sheetOneRowNumber = i + 2;
      sheetone.getRange('M' + sheetOneRowNumber).setValue(sheetOneColumnMValue);
    }
  }
}

Output:输出:

在此处输入图片说明

Note: Both produce the same output but using Sheet2 values as search key is more faster than the other.注意:两者产生相同的输出,但使用 Sheet2 值作为搜索键比另一个更快。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Google Sheets Scripts - 对于范围内的每个单元格,获取单元格具有特定值的行号,将行复制到范围内的第一个空白行 - Google Sheets Scripts - For each cell in range, get row number where cell has specific value, copy row to first blank row in range 谷歌表格脚本:为命名范围内的每个单元格获取 A1Notation - Google Sheets Script: Get A1Notation For Each Cell In Named Range 查找范围内值的匹配项并获取每个匹配项的第一个单元格和第一列值谷歌应用脚本 - Find matches to a value in a range and get first cell and first column values for each match google app script Google表格脚本-通过生成的值范围减少单元格的值 - Google Sheets Script - Decrease the Value of a Cell by a Generated Range of Values 获取范围内的x单元格谷歌表格应用程序脚本 - get x cell in range google sheets app script 谷歌表格脚本:从当前单元格获取多列/行命名范围 - Google Sheets Script: Get Multi-Col/Row Named Range from Current Cell Google 表格脚本:getRange().setValue(sampleArray) 仅将第一个单元格值复制到目标范围的单元格中 - Google Sheets Script: getRange().setValue(sampleArray) copies only first cell value into destination range's cells Apps 脚本 - 如何获取正确的标题范围以将值设置为单元格谷歌表格? - Apps Script - how to get the correct headers range to set the value to a cell google sheets? 在 Google 表格中移动单元格范围 - Shift Cell Range in Google Sheets 为范围内的每个单元格添加值(Google 应用程序脚本) - Add value to each cell in range (Google apps script)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM