Dynamic namedRange, Trying to print only cells with data in them

独自空忆成欢 提交于 2020-06-16 03:34:07

问题


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:

  • listDown is 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 your script, result.length[i] always becomes undefined.
  • At console.log(result), all values of result is 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 else was 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!