[英]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.我正在尝试将某些单元格从工作表 1(源工作表)复制到工作表 2(目标工作表),而不删除工作表 2 中的现有单元格。
I want to copy A5:A800 from sheet 1 to C7:C802 from sheet 2.我想将工作表 1 中的 A5:A800 复制到工作表 2 中的 C7:C802。
Conditions:状况:
My usage我的用法
I will add the script to a 'button'.我会将脚本添加到“按钮”。 My sheet 1 keeps getting updated automatically.
我的工作表 1 不断自动更新。 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).
有时我手动更改工作表 2 中的单元格。我不希望在按下按钮(运行脚本)时覆盖这些更改。
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"));
}
My approach would be to get the data of sheet2
and use map to fill in the empty values with the values of sheet1
:我的方法是获取
sheet2
的数据并使用map用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.我还添加了一个
onOpen()
function 来创建一个链接到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.我使用三元运算符来简化代码,并将工作表中的值平整十个,因为我们考虑列的值,因此一
1D
数组更有意义。
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.