4
votes

I have a Google spreadsheet and I am having real difficulty trying to work out the code I require to select a number of rows.

The only rows I want to select are the rows that have a value or formula in one of the columns (lets say column B).

I cannot order the sheet by the column and only select the first x values.

I am thinking I need to loop through every row in the sheet and determine if column B is empty but I don't know how to do this or how to check if the cell contains a value or a formula. If it contains a formula then this must be preserved in preference to the value.

How do I select only the rows from a Google Spreadsheet where values or formulas in a certain column are not empty using Google Apps Scripts?

2
What do you mean by "select the rows"? What do you want to do with them? As far as I know, there still isn't any way (script or otherwise) to select, as in "activate", non-contiguous cells in GSheets.AdamL

2 Answers

4
votes

This should do what you want... maybe it need some debugging because I didn't test it since I'm not sure about what you really want ;-)

function copynotempty(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = SpreadsheetApp.setActiveSheet(ss.getSheets()[0])
  var col = 1 ; // choose the column you want to check: 0 = col A, 1= col B ...
  var range = sh.getDataRange();
  var values=range.getValues();// data is a 2D array, index0 = col A
  var formulas=range.getFormulas();// data is a 2D array, index0 = col A
  var target=new Array();// this is a new array to collect data
   for(n=0;n<range.getHeight();++n){
     if (values[n][col]!=''|| formulas[n][col]!=''){ ; 
        for (cc=0;cc<range.getWidth();++cc){
                if (formulas[n][cc]!=''){target[n][cc]=formulas[n][cc]}else{target[n][cc]=values[n][cc]}
    // if the cell has a formula copy it or else copy the value, do that for the whole row
// (this also defines and apply the 'priority' you mentioned in your question, I wasn't sure if it should apply to the whole row or only on column B)
                }
              }
            }
            if(target.length>0){// if there is something to copy
          var sh2=SpreadsheetApp.setActiveSheet(ss.getSheets()[1]); //second sheet of your spreadsheet
          sh2.getRange(1,1,target.length,target[0].length).setValues();// paste the selected values in the 2cond sheet
          }
        }
1
votes

Try something on these lines - this code is not tested but will give you a fair idea

var sheet = // get sheet ; 
var data = sheet.getDataRange().getValues(); 
for ( var i = 0; i < data.length ; i++){
  if (data[i][1] != ''){  // Column B is at index 1
    // Do whatever you want
  }
}