通过for循环谷歌工作表脚本将行复制到另一个工作表

时间:2021-04-13 17:24:23

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

我是一个新手,已经尝试了多种方法,但我似乎无法弄清楚发生了什么。

我想要做的是将添加到一张纸 (Source) 的任何新行复制到另一张纸 (Target)。有一列 (7) 表示不要将该行从 Source 复制到 Target,并在程序运行并复制到 CP 时设置为 Target Target

下面的代码似乎可以工作并复制到 Source,但每次运行时它都会复制 CP 中的每一行,即使源行已设置为 {{第 7 列中的 1}}(CP 表示复制,如果您想知道的话)。

任何帮助我解决这个问题的帮助将不胜感激。我已经把头撞在桌子上好几次了,但这似乎也无济于事?。

function copyRowToTarget() {

  var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Source')
  var targetSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Target') 
  var startRow = 2; 
  var sSLastRow = sourceSheet.getLastRow();
  var con = sourceSheet.getRange(1, 7, sSLastRow); //col that indicates if it should be copied or not
  var conVals = con.getValues(); //con values
  var rangetocopy = sourceSheet.getRange(1, 1, sSLastRow, 6); 
  var rowstocopy = rangetocopy.getValues(); //values to copy
     

  for (var i = 1; i < conVals.length; i++){
    if (conVals[i] !== "CP"){
      targetSheet.appendRow(rowstocopy[i]);
    }
    sourceSheet.getRange(startRow + i, 7).setValue("CP");

  }
}

1 个答案:

答案 0 :(得分:1)

试试这个:

function copyRowToTarget() {
  const ss=SpreadsheetApp.getActive();
  const ssh = ss.getSheetByName('Source')
  const tsh = ss.getSheetByName('Target') 
  const startRow = 2; 
  const vals=ssh.getRange(startRow, 6, ssh.getLastRow() - startRow + 1, 2).getValues();
  vals.forEach((v,i)=>{
    if (v[1] != "CP"){
      tsh.appendRow([v[0]]);
      ssh.getRange(startRow + i, 7).setValue("CP");
    }
  });
}

我测试了这个版本:

function copyRowToTarget() {
  const ss=SpreadsheetApp.getActive();
  const ssh = ss.getSheetByName('Sheet1')
  const tsh = ss.getSheetByName('Sheet2') 
  const startRow = 2; 
  const vals=ssh.getRange(startRow, 6, ssh.getLastRow() - startRow + 1, 2).getValues();
  vals.forEach((v,i)=>{
    if (v[1] != "CP"){
      tsh.appendRow([v[0]]);
      ssh.getRange(startRow + i, 7).setValue("CP");
    }
  });
}

工作正常:

数据:

<头>
COL1 COL2 COL3 COL4 COL5 COL6 COL7 COL8 COL9 COL10
6 13 10 27 1 17 CP 8 25 0
0 0 12 16 26 1 CP 25 14 5
2 8 10 25 6 20 CP 10 3 0
16 15 21 12 2 1 CP 9 15 0
29 10 9 10 25 23 CP 27 29 6
28 24 4 13 2 26 CP 23 19 19
29 17 3 0 9 1 CP 3 27 15
20 8 7 15 28 26 CP 10 24 13
27 16 29 2 25 14 CP 21 4 12

表 2:

<头>
17
1
20
1
23
26
1
26
14
13