Google apps script 对于每行,添加重复项,更改2个单元格
我有一堆行,我想附加重复项,除了更改两个单元格。 我需要每个人为每个24岁和36岁的孩子排15000、20000、25000人的队(如果这有意义的话?) 输入:Google apps script 对于每行,添加重复项,更改2个单元格,google-apps-script,Google Apps Script,我有一堆行,我想附加重复项,除了更改两个单元格。 我需要每个人为每个24岁和36岁的孩子排15000、20000、25000人的队(如果这有意义的话?) 输入: A B C D 1 15000 24 Susan Smith 2 15000 24 John Deer 预期产量 A B C D
A B C D
1 15000 24 Susan Smith
2 15000 24 John Deer
预期产量
A B C D
1 15000 24 Susan Smith
2 20000 24 Susan Smith
3 25000 24 Susan Smith
4 15000 36 Susan Smith
5 20000 36 Susan Smith
6 25000 36 Susan Smith
7 15000 24 John Deer
8 20000 24 John Deer
9 25000 24 John Deer
10 15000 36 John Deer
11 20000 36 John Deer
12 25000 36 John Deer
我知道我需要为每一行执行一个复制和追加该行的函数,但我不确定这是如何实现的。我相信您的目标如下
- 您希望在问题中实现转换
- 例如,当列“C”和“D”的值分别为
和Susan
时,您希望将以下值放入电子表格Smith
15000 24 Susan Smith 20000 24 Susan Smith 25000 24 Susan Smith 15000 36 Susan Smith 20000 36 Susan Smith 25000 36 Susan Smith
- 例如,当列“C”和“D”的值分别为
- 您希望使用谷歌应用程序脚本实现这一点
15000、20000、25000和24、36
的值来输入值
srcSheetName
和dstSheetName
的变量,并运行myFunction
的函数
function myFunction() {
const srcSheetName = "Sheet1"; // Please set the source sheet name.
const dstSheetName = "Sheet2"; // Please set the destination sheet name.
const ss = SpreadsheetApp.getActiveSpreadsheet();
// 1. Retrieve the values from the columns "C" and "D".
const srcSheet = ss.getSheetByName(srcSheetName);
const values = srcSheet.getRange("C1:D" + srcSheet.getLastRow()).getValues();
// 2. Remove the empty rows.
const v = values.filter(([c,d]) => c && d);
// 3. Create an array for putting values using the values of `15000, 20000, 25000` and `24, 36` for the columns "A" and "B", respectively.
const colA = [15000, 20000, 25000];
const colB = [24, 36];
const res = v.reduce((ar, [c,d]) => {
colB.forEach(b => colA.forEach(a => ar.push([a, b, c, d])));
return ar;
}, []);
// 4. Put the values to the destination sheet.
const dstSheet = ss.getSheetByName(dstSheetName);
dstSheet.getRange(1, 1, res.length, res[0].length).setValues(res);
}
注:
- 如果要将上述脚本用作自定义函数,还可以使用以下脚本。在这种情况下,请将以下脚本复制并粘贴到电子表格的脚本编辑器中。并且,请将自定义函数
放入单元格。由此,获得结果值=SAMPLE(C1:D)
const SAMPLE = values => values .filter(([c,d]) => c && d) .reduce((ar, [c,d]) => { [24, 36].forEach(b => [15000, 20000, 25000].forEach(a => ar.push([a, b, c, d]))); return ar; }, []);