如何在操作时保持同步的同时将工作表数据复制到另一个?

时间:2019-07-18 16:23:32

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

我目前有存储所有主要数据的sheet1,我想将数据复制到sheet2,sheet3等。我用来将sheet1复制到其他工作表的当前代码是:

=IMPORTRANGE("sheetID","Sheet1!A1:Z")

尽管它可以使工作表之间的数据保持同步,但问题是当您尝试在已导入的=IMPORTRANGE工作表上进行编辑时,

#REF!

"Array result was not expanded because it would overwrite data in CELL VALUE."

那么有没有办法使所有工作表在同时编辑时保持同步?

编辑:使用Google脚本或公式都可以。

1 个答案:

答案 0 :(得分:0)

尝试在AppScript中这样做:

function copySheet1(){ //Run this once to copy Sheet1 to all the others

  var sprsheet = SpreadsheetApp.openById("sheet-id");
  var all_sheets = sprsheet.getSheets();

  var values = all_sheets[0].getRange("A1:Z").getValues(); //Get values of Sheet1

  for (var i = 1; i < all_sheets.length; i++){
    all_sheets[i].getRange("A1:Z").setValues(values);

 }
}

function onEdit(e) { //This will run with any sheet you edit

  var edited_sheet = e.source.getSheetName(); //Gets the name of the sheet edited
  var all_sheets = e.source.getSheets();

  var range = e.range.getA1Notation(); //Gets the Cell you edited
  var cell_value = e.range.getValue(); //Gets the value of the cell

  for (var i = 0; i < all_sheets.length; i++){ //Iterates over all the sheets and copies the value to the same cell for each one
    var sheet = all_sheets[i];

    if (sheet.getSheetName() != edited_sheet){ //There is no need to rewrite the cell of the sheet edited
      sheet.getRange(range).setValue(cell_value);
    }
  }
}