[英]Google Sheets / Javascript -> Loop through array and set the values to the cells
I am new to programming and I have such a simple question but I struggle to find the answer.我是编程新手,我有一个如此简单的问题,但我很难找到答案。 I would like to dynamically overwrite cells from A1 on until the lenght of the array.
我想从 A1 开始动态覆盖单元格,直到数组的长度。 This is the second for loop I am struggling with.
这是我正在努力解决的第二个 for 循环。 The combination of ("A" + ii) for the range doesnt look "professional" :-) Thanks for your help.
该系列的 ("A" + ii) 组合看起来并不“专业”:-) 感谢您的帮助。
function selectmyagency() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var agencynames = ss.getRange("B8:B42").getValues();
var myagency = ss.getRange("C3").getValue();
var arrayLength = agencynames.length;
for (var i = 0; i < arrayLength; i++) {
if(agencynames[i] == myagency){
//doNothing
} else {
agencynames[i] = ".";
}//endif
}//endfor
//overwrite Cell in Spreadsheet
for (var ii = 0; ii < agencynames.length; ii++) {
SpreadsheetApp.getActiveSheet().getRange("A"+ii).setValue(agencynames[ii]);
//SpreadsheetApp.getActiveSheet().getRange("A9").setValue(agencynames[ii]);
//SpreadsheetApp.getActiveSheet().getRange("A10").setValue(agencynames[ii]);
}
}//endfunction
Instead of looping through the array and setting the ranges value one cell at a time, you can do this in a batch operation like so: ss.getRange("B8:B42").setValues(agencynames);
您可以像这样在批处理操作中执行此操作,而不是遍历数组并一次设置一个单元格的范围值:
ss.getRange("B8:B42").setValues(agencynames);
Do this after modifying the agencynames
array, this will set all the values of that range to match your array as long as the array and the range are the same size.在修改机构
agencynames
数组后执行此操作,只要数组和范围大小相同,就会将该范围的所有值设置为与您的数组匹配。 It's generally discouraged to make calls to a service in a loop when you can use a batch operation, for performances and readabilities sake.当您可以使用批处理操作时,通常不鼓励在循环中调用服务,以提高性能和可读性。
For more information, refer to the Apps Script Best Practices有关更多信息,请参阅Apps 脚本最佳实践
Edit: Your modified code:编辑:您修改后的代码:
function selectmyagency() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var agencynames = ss.getRange("B8:B42").getValues();
var myagency = ss.getRange("C3").getValue();
var arrayLength = agencynames.length;
for (var i = 0; i < arrayLength; i++) {
if(agencynames[i] == myagency){
//doNothing
} else {
agencynames[i] = ".";
}//endif
}//endfor
//overwrite Cell in Spreadsheet
ss.getRange("B8:B42").setValues(agencynames);
}//endfunction
A couple more pointers:还有一些提示:
getValues()
you are getting an array of arrays not an array of values, even if it is only a single column.getValues()
您得到的是数组数组而不是值数组,即使它只是一列。 ie. [["value"],["value"],["value"]]
instead of ["value","value","value"]
. [["value"],["value"],["value"]]
而不是["value","value","value"]
。 When setting or getting the values of this array, you probably want to use agencynames[i][0]
instead of agencynames[i]
agencynames[i][0]
而不是机构agencynames[i]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.