简体   繁体   中英

Google Spreadsheets script - How to copy range from one sheet to another sheet, but without overwriting non-empty target cells

I'm trying to copy certain cells from sheet 1 (source sheet) to sheet 2 (target sheet), without deleting existing cells in sheet 2.

I want to copy A5:A800 from sheet 1 to C7:C802 from sheet 2.

Conditions:

  • One-to-one copying: So for example, content of cell A25 goes to cell C27.
  • No overwriting: if C27 already has a value or text, it should stay like that. A25 doesn't get copied. The script should skip non-empty cells.
  • A cell with a zero should not be considered as an empty cell.

My usage

I will add the script to a 'button'. My sheet 1 keeps getting updated automatically. Sometimes I manually change cells in sheet 2. I don't want those changes to be overwritten when I press the button (run the script).

function CopyCells() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  
  var sheet1 = ss.getSheetByName("sheet1"); //source sheet
  var sheet2 = ss.getSheetByName("sheet2"); //target sheet

  //missing for loop magic
  
  var getCopyRange = sheet1.getRange("A5:A800");
  getCopyRange.copyTo(sheet2.getRange("C7:C802"));

}

Explanation:

  • My approach would be to get the data of sheet2 and use map to fill in the empty values with the values of sheet1 :

     vals2.map((v,i)=>[v==''?vals1[i]:v]);

    For the non-empty values keep the original values.

  • I also added an onOpen() function to create a menu button linked to the CopyCells function.

  • I use a ternary operator to simplify the code and I flat ten the values from the sheets since we consider values of a column and therefore a 1D array makes more sense.

Solution:

function CopyCells() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet1 = ss.getSheetByName("sheet1"); //source sheet
  const sheet2 = ss.getSheetByName("sheet2"); //target sheet
  const range1 = sheet1.getRange('A5:A800');
  const range2 = sheet2.getRange('C7:C802');
  const vals1 = range1.getValues().flat();
  const vals2 = range2.getValues().flat();
  const fvals = vals2.map((v,i)=>[v==''?vals1[i]:v]);
  range2.clearContent();
  range2.setValues(fvals);
}
 
function onOpen() {
  SpreadsheetApp.getUi()
  .createMenu('Button')
  .addItem('Copy Cells', 'CopyCells')
  .addToUi();
}

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