簡體   English   中英

通過for循環谷歌表格腳本將行復制到另一張表格

[英]Copy row to another sheet via for loop google sheets script

我是新手,已經嘗試了幾種方法,但我似乎無法弄清楚發生了什么。

我想要做的是將添加到一張紙( Source )的任何新行復制到另一張紙( Target )。 有一列 (7) 指示不要將該行從Source復制到Target ,並且在程序運行並復制到Target時設置為CP

下面的代碼似乎可以工作並復制到Target ,但每次我運行它時它都會從Source復制每一行,即使在第 7 列中將源行設置為CP (如果您想知道, 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");

  }
}

試試這個:

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");
    }
  });
}

工作正常:

數據:

列1 列2 列3 列4 COL5 列6 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2025 STACKOOM.COM