问题
function readNamedRange() {
var app = SpreadsheetApp;
var activeSheet = app.getActiveSpreadsheet().getActiveSheet();
var listDown = activeSheet.getRange("listDown");
var result = activeSheet.getRange("listDown").getValues();
}
In the above code, my active sheet contains a namedRange which has the entire B column set to the namedRange called listDown. Cells B1 to B10 have data 1 through 10 in them. I am trying to print only data cells with values in them using both for loop and an if statement inside it. I have tried the following logic given below:
for(var i=0; i <result.length; i++){
if(result.length[i] != "" && result.length[i] != undefined ){
console.log(result);
}else{
console.log("namedRange is empty");
}
}
My above logic is not complete and I am unable to understand how to do it.
回答1:
I believe your goal as follows.
- You want to show the values of cells except for the empty cells at the log.
For this, how about this modification?
Modification points:
listDownis not used in your script.- The value retrieved by
getValues()is 2 dimensional array. And your range is one column.- In this case, each value can be retrieved by
result[i][0].
- In this case, each value can be retrieved by
- In your script,
result.length[i]always becomesundefined. - At
console.log(result), all values ofresultis shown. - In your case,
result[i][0] != ""can be used for the if statement.
When above points are reflected to your script, it becomes as follows.
Modified script:
function readNamedRange() {
var activeSheet = SpreadsheetApp.getActiveSheet();
var result = activeSheet.getRange("listDown").getValues();
for (var i = 0; i < result.length; i++) {
if (result[i][0] != "") { // Modified
console.log(result[i][0]); // Modified
} else {
console.log("namedRange is empty");
}
}
}
References:
- getValues()
- Array
Added:
- You want to show the values of only cells except for the empty cells.
For this, how about the following modified script?
- The script in
elsewas removed. - In order to reduce the process cost,
var end = activeSheet.getLastRow()is used for the for loop.
Modified script:
function readNamedRange() {
var activeSheet = SpreadsheetApp.getActiveSheet();
var result = activeSheet.getRange("listDown").getValues();
var end = activeSheet.getLastRow();
for (var i = 0; i < end; i++) {
if (result[i][0] != "") {
console.log(result[i][0]);
}
}
}
来源:https://stackoverflow.com/questions/61906664/dynamic-namedrange-trying-to-print-only-cells-with-data-in-them