根据多个条件将行从所有工作表复制到另一工作表

时间:2020-09-01 02:38:53

标签: google-apps-script google-sheets

我需要根据多种条件将行从所有工作表复制/导入到一张不同的工作表中。

换句话说,我需要从电子表格上所有现有的表格中自动复制/导入B列为“水果”而C列为“红色”的行。

我可以这样从Sheet1导入行:

=FILTER(
IMPORTRANGE("1HXbrA_Ks8yuIit6UOBdZEdan3hSRGnnuGvrIueDCbXM";"Sheet1!A2:C") ; 
           (Sheet1!B2:B = "fruit");(Sheet1!C2:C = "red")
)

但是我需要从所有现有的工作表中导入相应的行。

也许使用脚本是实现此目的的正确方法,但我无法做到这一点。

以下是用于测试的实时电子表格:

https://docs.google.com/spreadsheets/d/1HXbrA_Ks8yuIit6UOBdZEdan3hSRGnnuGvrIueDCbXM/edit?usp=sharing

此测试电子表格只有2张纸,但实际电子表格只有几张纸,因此请考虑在内。

非常感谢您。

2 个答案:

答案 0 :(得分:2)

我相信您的目标如下。

  • 您要检索在“ B”和“ C”列中分别有fruitred的行。
  • 您要将检索到的行放入目标表。
  • 您要使用Google Apps脚本实现以上目标。

流量:

此示例脚本的流程如下。

  1. 检索所有工作表。
  2. 从每个工作表中,检索在“ B”和“ C”列中分别具有fruitred的行。
    • 目前,destinationSheetName个工作表已被排除。
  3. 将检索到的行放入目标表。

示例脚本:

在使用此脚本之前,请设置destinationSheetName。并且在此示例脚本中,共享电子表格中的destinationSheetName和“ MERGED RED FRUITS”工作表被排除在行之外。

function myFunction() {
  const destinationSheetName = "MERGED RED FRUITS (DESIRED RESULT)";
  const excludeSheetNames = [destinationSheetName, "MERGED RED FRUITS"];
  
  // 1. Retrieve all sheets.
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheets = ss.getSheets();
  
  // 2. From each sheet, retrieve the rows which have `fruit` and `red` in the columns "B" and "C", respectively.
  const values = sheets.reduce((ar, s, i) => {
    if (!excludeSheetNames.includes(s.getSheetName())) {
      const [,...v] = s.getDataRange().getValues();
      const temp = v.filter(([,b,c]) => b == "fruit" && c == "red");
      if (temp.length > 0) ar = ar.concat(temp);
    }
    return ar;
  }, []);
  
  // 3. Put the retrieved rows to the destination sheet.
  const dest = ss.getSheetByName(destinationSheetName);
  dest.getRange(2, 1, values.length, values[0].length).setValues(values);
}

注意:

  • 在此示例脚本中,不检查值的重复。请注意这一点。
  • 当我在共享电子表格中看到当前脚本时,似乎在循环中使用了getValue()。在这种情况下,处理成本将很高。因此,我提出了以上流程。

参考文献:

答案 1 :(得分:1)

以下是一个脚本,它将执行我认为您想要的操作:

function myFunction() {
  var ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/1HXbrA_Ks8yuIit6UOBdZEdan3hSRGnnuGvrIueDCbXM/edit'); 
  var sheet = ss.getSheets()[0];
  let currentRow = 2;
  let rows = []
  while(sheet.getRange("B" + currentRow).getValue() != "") {
    if(sheet.getRange("B" + currentRow).getValue() == "fruit" && sheet.getRange("C" + currentRow).getValue() == "red") {
      rows.push(currentRow)
      console.log("Match " + currentRow);
    }
    currentRow++;
  }
  Logger.log(rows)
  let destSheet = ss.getSheetByName('TEST');
  let deststartRow=5;
  for(var row of rows) {
    sheet.getRange("A"+row +":C"+row).copyTo(destSheet.getRange("A"+deststartRow +":C"+deststartRow))
    deststartRow++;
  }
 
}