我有一個主串列,第 2 行中有幾十個名字,分布在一堆列 (A2:Z2) 中。每個名稱下都有一個值和資料串列。
| 第 2 行 | 約翰 | 莎莉 | 詹姆士 |
|---|---|---|---|
| 第 3 行 | 價值 | 價值 | 價值 |
| 第 4 行 | 價值 | 價值 | 價值 |
| 第 5 行 | 價值 | 價值 | |
| 第 6 行 | 價值 | 價值 |
每個名稱都應創建到作業表中。
這是用于為第 2 行中的每個名稱創建作業表的腳本:
function generateSheetByName() {
const ss = SpreadsheetApp.getActive();
var mainSheet = ss.getSheetByName('Master List');
const sheetNames = mainSheet.getRange(2, 1, mainSheet.getLastRow(), 1).getValues().flat();
sheetNames.forEach(n => ss.insertSheet(n));
}
我希望此腳本不僅為每個名稱創建一個作業表,而且還將每個名稱下的所有值一直向下傳遞到相應列的最后一行。
例如,John 在 A2 中,A3:A 是應轉移到創建的作業表中的值。Sally 是 B2 和 B3:B 是應該結轉的值。
在約翰的作業表中 - “約翰”是 A1 中的標題,列值位于 A2:A 中
對于制作的每張紙,我還想手動添加其他值。例如,如果創建了“John”作業表,并在 A2:A22 中添加了 20 個值,我希望腳本在 B2:B22 中添加復選框。或者總是在 B1 中添加一個公式,比如“=counta(a2:a)”之類的。
我怎樣才能用一個有效的回圈來做到這一點?請注意,這可能會創建 50 張紙并在每張紙上攜帶 10-50 個值
示例影像:
主串列:


每個名稱都將創建一個看起來像這樣的作業表
約翰的表
uj5u.com熱心網友回復:
我相信你的目標如下。
- 您想使用 Google Apps 腳本實作從第一張圖片到第二張圖片。
- 將值放入創建的作業表時,您希望將復選框插入“B”列,并將公式放入單元格“B1”。
- 您希望降低腳本的處理成本。
在這種情況下,以下示例腳本如何?
示例腳本:
在這個示例腳本中,為了降低腳本的處理成本,我使用了 Sheets API。當使用 Sheets API 時,流程成本將能夠降低一點。因此,在您使用此腳本之前,請在 Advanced Google services 中啟用 Sheets API。
function generateSheetByName() {
// 1. Retrieve values from "Master List" sheet.
const ss = SpreadsheetApp.getActive();
const mainSheet = ss.getSheetByName('Master List');
const values = mainSheet.getRange(2, 1, mainSheet.getLastRow(), mainSheet.getLastColumn()).getValues();
// 2. Transpose the values without the empty cells.
const t = values[0].map((_, c) => values.reduce((a, r) => {
if (r[c]) a.push(r[c]);
return a;
}, []));
// 3. Create a request body for using Sheets API.
const requests = t.flatMap((v, i) => {
const sheetId = 123456 i;
const ar = [{ addSheet: { properties: { sheetId, title: v[0] } } }];
const temp = {
updateCells: {
range: { sheetId, startRowIndex: 0, startColumnIndex: 0 },
fields: "userEnteredValue,dataValidation"
},
};
temp.updateCells.rows = v.map((e, j) => {
if (j == 0) {
return { values: [{ userEnteredValue: { stringValue: e } }, { userEnteredValue: { formulaValue: "=counta(a2:a)" } }] }
}
const obj = typeof (e) == "string" || e instanceof String ? { stringValue: e } : { numberValue: e }
return { values: [{ userEnteredValue: obj }, { dataValidation: { condition: { type: "BOOLEAN" } } }] }
});
return ar.concat(temp);
});
// 4. Request to the Sheets API using the created request body.
Sheets.Spreadsheets.batchUpdate({requests}, ss.getId());
}
筆記:
- 在此示例腳本中,我使用了您的示例輸入和輸出情況。所以當這些結構與您的實際情況不同時,腳本可能無法使用。請注意這一點。
參考:
- 方法:電子表格.batchUpdate
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/350476.html
標籤:javascript 谷歌应用程序脚本 谷歌表格 google-sheets-api
下一篇:在MATCH評估中沒有發現價值
