我是谷歌脚本的新手,我遇到了一些我无法弄清楚的东西。我试图命名一个范围,希望最终将它放入一个数组并用数据填充另一张表。
我遇到了命名范围的问题。我希望最终能够迭代并命名许多范围,所以我希望能够使用变量作为行号。
如果我试试这个:
var rngProject = "A8:Y21";
var RngName = "project1";
然后一切正常,我将数据放在一个数组中。但是,如上所述,我想使用变量作为行号以及范围名称,如下所示。
如果我试试这个:
var rngProject = "A" + strtRow + ":Y" + totRows + strtRow - 1;
var RngName = "project" + toString(i);
在这一行:
var rng_to_name = active_spreadsheet.getSheetByName(sheet_name).getRange(address);
我收到错误:“参数必须是一个范围。”在调试器中,地址值显示为NaN,所以我认为这是不对的。但我也尝试过使用strRange(下面已注释掉),我在同一行上得到了同样的错误。
有没有办法可以将这个值转换为范围类型,或者还有其他我做错的事情?
function namePrjRange () {
var i = 1
var strtRow = 8;
var shtName = "USER INPUT by week: TEST";
var totRows = 14;
//var strRange = "A" + toString(strtRow) + ":Y" + toString(totRows + strtRow - 1);
var rngProject = "A" + strtRow + ":Y" + totRows + strtRow - 1;
var RngName = "project" + toString(i);
//Logger.log(strRange);
Logger.log(rngProject);
Logger.log(RngName);
nameRange(shtName, rngProject, RngName);
}
// Given a sheet name (assumed to be in the active spreadsheet, an address using "A1" notation,
// and a name string, assign that name to the range address in the given sheet.
function nameRange(sheet_name, address, rng_name) {
// Create an spreadsheet object.
Logger.log("Entered nameRange function")
var active_spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// Get a range object by firstly getting a sheet object from the spreadsheet object and then pass the
// "address" argument to the sheet "getRange()" method.
var rng_to_name = active_spreadsheet.getSheetByName(sheet_name).getRange(address);
// Use the spreadsheet object method "setNamedRange()" to assign a range name to a range object.
Logger.log("About to set Named Range");
Logger.log(rng_name);
Logger.log(rng_to_name);
active_spreadsheet.setNamedRange(rng_name, rng_to_name);
}
答案 0 :(得分:1)
使用:
var rngProject = "A" + strtRow + ":Y" + (totRows + strtRow - 1);
当你在这里执行字符串连接时,解析器会尝试将所有内容连接在一起(即实际上并没有将totRows添加到strtRow),并且当它到达减号时最终丢弃它的bundle,这是一个有效的字符串运营商。所以你只需要在算术部分周围加上括号。
https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators#String_operators