我試圖從源范圍粘貼到目標范圍,但跳過目標中的一列并將值保留在其中(在附加的示例中,我想將值保留在 C 列(其他列)中。但找不到方法保留這些值或完全跳過該列。這是我正在使用的代碼:
function appendSheet1ToSheet2() {
const ss = SpreadsheetApp.getActive();
const source = ss.getRange('Sheet1!A1:C');
const target = ss.getRange('Sheet2!A1:D');
appendUniquesToRange_(source, target);
}
function appendUniquesToRange_(sourceRange, targetRange) {
const dataToAppend = sourceRange.getValues().map(row => [row[0], row[1], ,row[2]]);
const existingData = targetRange.getValues()
const newData = existingData
.concat(dataToAppend)
.filter((row, rowIndex, array) =>
array
.map(tuple => tuple[0])
.indexOf(row[0]) === rowIndex && row[0] !== ''
);
targetRange
.offset(0, 0, newData.length, newData[0].length)
.setValues(newData);
}
我試過將目標定義為范圍串列,但隨后在第二個函式“TypeError: targetRangeList.getValues is not a function”中出現其他錯誤
const target = ss
.getRangeList(['Sheet2!A1:B', 'Sheet2!D1:D'])
.getRanges()
.map(range => range.getValues());
無法弄清楚如何解決它。
uj5u.com熱心網友回復:
我相信你的目標如下。
- 您想將源作業表中的值放到目標作業表中。此時,您要跳過目標作業表的“C”列。
在你的情況下,下面的修改如何?
修改后的腳本 1:
在本次修改中,請appendUniquesToRange_進行如下修改。
function appendUniquesToRange_(sourceRange, targetRange) {
const dataToAppend = sourceRange.getValues();
const [header, ...existingData] = targetRange.getValues();
const newData = [header, ...dataToAppend.map((r, i) => [r[0], r[1], existingData[i][2], r[2]])];
console.log(newData)
targetRange
.offset(0, 0, newData.length, newData[0].length)
.setValues(newData);
}
修改后的腳本 2:
在本次修改中,請appendSheet1ToSheet2進行如下修改。
function appendSheet1ToSheet2() {
const ss = SpreadsheetApp.getActive();
const source = ss.getRange('Sheet1!A1:C');
const target = ss.getSheetByName('Sheet2');
const {ab, d} = source.getValues().reduce((o, r) => {
const temp = r.splice(0, 2);
o.ab.push(temp);
o.d.push(r);
return o;
}, {ab: [], d: []});
target.getRange(2, 1, ab.length, ab[0].length).setValues(ab);
target.getRange(2, 4, d.length, d[0].length).setValues(d);
}
- 在此模式中,使用
getValuesand檢索和放置值setValues,并且目標表的“C”列不會更改。
修改后的腳本 3:
在本次修改中,請appendSheet1ToSheet2進行如下修改。
function appendSheet1ToSheet2() {
const ss = SpreadsheetApp.getActive();
const source = ss.getSheetByName("Sheet1").getRangeList(["A1:B", "C1:C"]).getRanges();
const target = ss.getSheetByName('Sheet2').getRangeList(["A2", "D2"]).getRanges();
source.forEach((r, i) => r.copyTo(target[i]));
}
- 在此模式中,使用 復制值
copyTo,并且目標作業表的“C”列不會更改。
筆記:
- 請根據您的實際情況選擇上述腳本之一。
參考:
- 地圖()
- 減少()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/400078.html
