Try this one:
function TestNextNonBlank() {
var spreadsheet = SpreadsheetApp.getActive();
var mysheet=spreadsheet.getSheetByName('MainSheet');
var myrange=mysheet.getRange('Q1');
myrange=nextNonBlank(myrange); //First Non Blank
Logger.log(myrange.getA1Notation()); //Give Q15
myrange=nextNonBlank(myrange); //Second Non Blank
Logger.log(myrange.getA1Notation()); //Give Q16
myrange=nextNonBlank(myrange); //Third Non Blank
Logger.log(myrange.getA1Notation()); //Give Q994
};
function nextNonBlank(theRange)
{
if (theRange.offset(1, 0).isBlank()==false) return theRange.offset(1, 0);
theRange=theRange.offset(1, 0);
if (theRange.offset(1, 0).isBlank()==false) return theRange.offset(1, 0);
theRange=theRange.getNextDataCell(SpreadsheetApp.Direction.DOWN);
return theRange;
}
To Avoid the invalid argument error, below I have modified the script of function, after this function reach the max row, it return the range in the max row position. To have the script run well, we must ensure the valid sheet and the valid position of non blank cell:
function nextNonBlank(theRange)
{
if (theRange.getSheet().getMaxRows()==theRange.getRowIndex()){
return theRange;
}
//save the range as last range
var storedRange=theRange;
if (theRange.offset(1, 0).isBlank()==false) return theRange.offset(1, 0);
theRange=theRange.offset(1, 0);
if (theRange.offset(1, 0).isBlank()==false) return theRange.offset(1, 0);
theRange=theRange.getNextDataCell(SpreadsheetApp.Direction.DOWN);
//if the reach range is blank, back to use the stored range
if (theRange.isBlank()) theRange=storedRange;
return theRange;
}
column
ofThere is data in that column on rows 1, 15, and 16 ONLY.
? In your script, the column "Q" is used. So whencolumn
is not the column "Q",getNextDataCell(SpreadsheetApp.Direction.DOWN)
doesn't return "Q15". How about this? – TanaikeDOWN
, and it is fine. Moved the cursor to Q15 as expected – Tedinoz