简体   繁体   中英

Google Apps Script - onEdit using an Array to Copy data one sheet to another

Due to my sheet names continually changing i would like to use an onEdit to copy from one sheet to another over 10 tabs

I have tried to modify the below script to do what i need but just cant find where i am going wrong.

so if anyone checks a box in Column 36 of any of the 10 tabs the code copies that row to the Master sheet

  function CopyRange(e) {
  var range = e.range;
  var sheet = range.getSheet()[6, 16];
    if (sheet.getSheetName() == [6, 16] && range.columnStart == 36 && range.rowStart >= 2 && e.value 
    == "TRUE") {
  var [[]] = sheet.getRange(range.rowStart, 1, 1).getValues();
  e.source.getSheetByName("Master").appendRow([]);
    }
  }

Explanation / Issues:

There are a couple of issues with your approach:

  • var sheet = range.getSheet()[6, 16]; is not a valid way to slice an array. Instead use slice getSheets().slice(6,16) .

  • sheet.getSheetName() == [6, 16] this line is also not valid. You are comparing a name ( String ) with an array. Instead you want to check if the name of the active sheet belongs to the list of the sheet names. First you need to get all the sheet names using map :

    const all_sheets = e.source.getSheets().slice(6,16).map(sh=>sh.getName());

    and then using includes you can check if the name of the active sheet belongs to all_sheets array:

    all_sheets.includes(active_sh.getName())

  • var [[]] = sheet.getRange(range.rowStart, 1, 1).getValues(); this line is also not valid. What you want is to store the data to a variable. But first you need to convert it to a 1D array since this is the type of argument that appendRow accepts. Therefore you need to flat ten it:

     const data = active_sh.getRange(row,1,1,active_sh.getLastColumn()).getValues().flat(); master_sh.appendRow(data);
  • Finally, you probably want to rename CopyRange to onEdit in order to make it work, unless you have an installable onEdit trigger attached to CopyRange .

Solution:

function onEdit(e) {
  const row = e.range.rowStart;
  const col = e.range.columnStart;
  const master_sh = e.source.getSheetByName("Master")
  const active_sh = e.source.getActiveSheet();
  const all_sheets = e.source.getSheets().slice(6,16).map(sh=>sh.getName());

  if(all_sheets.includes(active_sh.getName()) && col == 36 && row > 1 && e.value == 'TRUE'){
  const data = active_sh.getRange(row,1,1,active_sh.getLastColumn()).getValues().flat();
  master_sh.appendRow(data);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM