如何解决Google Script - 在电子表格中自动创建新工作表后在预定义单元格中设置公式 可能的解决方案参考
假设我有一个 masterSheet,其名称在 A 列中,在 B 列中有一个链接,从第 2 行开始。 我希望对于在 masterSheet 中添加的每一行,它都会自动:
- 创建具有 A 列中人员姓名的新工作表
- 在这个新创建的工作表中设置 A 和 B 的值
- 在 C 中设置我的 IMPORTRANGE 公式
- 在 J2:J50 中设置我的 CONCATENATE 公式
第 1 点和第 2 点运行良好。第 3 点和第 4 点根本不起作用,我收到这样的错误消息:TypeError: sheetNames.getRange is not a function
我不知道这有什么问题,但我很确定它来自我将它们放入循环的地方或其他东西。
有人可以帮我解决这个问题吗?
function createNewSheets() {
// 1. Retrieve the current sheet names.
var dataSheet = SpreadsheetApp.getActiveSpreadsheet();
var sheetNames = dataSheet.getSheets().map(s => s.getSheetName());
// 2. Retrieve the values from "mastersheet" sheet.
var masterSheet = dataSheet.getSheetByName('Liste de nageurs');
var values = masterSheet.getRange('A2:B' + masterSheet.getLastRow()).getValues();
// Imports table from link
var swimmerTable = '=IMPORTHTML(B1;"table";4)'
// Concatenates event with pool size
var fullName = 'CONCATENATE(C2;" - ";D2)'
// 3. Using the retrieved sheet names and values,the new sheets are inserted and the values are put.
values.forEach(r => {
if (!sheetNames.includes(r[0])) {
dataSheet.insertSheet(r[0]).appendRow(r);
sheetNames.push(r[0]);
// Sets the formula in the 3rd column:
sheetNames.getRange(1,3).setFormula(swimmerTable)
// Sets the formula2 and iterates it from row 2 to row 50
sheetNames.getRange("J2:J50").setFormula(fullName)
}
});
}
解决方法
可能的解决方案
我认为错误就在这里:
dataSheet.insertSheet(r[0]).appendRow(r);
sheetNames.push(r[0]);
// Sets the formula in the 3rd column:
sheetNames.getRange(1,3).setFormula(swimmerTable)
// Sets the formula2 and iterates it from row 2 to row 50
sheetNames.getRange("J2:J50").setFormula(fullName)
既然你说你收到的错误是
TypeError: sheetNames.getRange is not a function
这似乎是因为您的变量 sheetNames
可能如下所示:
["sheet1","sheet2",...]
这些只是“字符串”(纯文本)而不是工作表对象。所以他们没有方法 getRange
。
您可以将其更改为:
var newSheet = dataSheet.insertSheet(r[0])
sheetNames.push(r[0]);
newSheet.appendRow(r);
newSheet.getRange(1,3).setFormula(swimmerTable)
newSheet.getRange("J2:J50").setFormula(fullName)
这里您将 dataSheet.insertSheet
的返回值分配给一个变量。此方法的返回值是新的工作表对象。
总而言之,我相信在您的代码中,您将工作表名称(它只是文本)的概念与具有 getRange
方法的工作表对象等混为一谈.
参考
,试试这个:
const fullName = '=C2 & " - " & D2)';
// ...
const sheet = dataSheet.insertSheet(r[0]).appendRow(r);
// ...
sheet.getRange(1,3).setFormula(swimmerTable);
sheet.getRange("J2:J50").setFormula(fullName);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。