1

I have just started trying out the script editor of the Google Sheets.

Here is what I am trying to do: I have a few "headers" in Sheet A. I will name them Header A, B, and C.

1 | Header A
2 | text 1
3 | text 2
4 | (empty row)
5 | Header B
6 | text 1
7 | text 2
8 | (empty row)
9 | Header C
10 | text 1
11 | text 2

Sheet B

1 | text 1 | date | Header A
2 | text 2 | date | Header B
3 | text 3 | date | Header B
4 | text 4 | date | Header C
5 | text 5 | date | Header A

When I update my data on Sheet B, it will be automatically be updated on Sheet A based on my custom attributes in Sheet B. I need it to be able to update the data on Sheet B onto Sheet A's empty row after the specific Headers.

Currently I am stuck at getting the next empty row in Sheet A. I am able to get the row that my Headers are in but I couldn't find any help online finding the next empty row after each specific Headers.

I could not find any classes that is provided. All I can see is getLastRow which is not what I want. I wonder can this be done?

Below is my current code:

function getScheduleStatus(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var name = ss.getSheetByName("Production Schedule");
  var rng = name.getDataRange();
  var last_row = rng.getLastRow();
  var data = rng.getValues();
  var str_upcoming = "upcoming"
  var rows = [];

  for (var i=0; i < data.length; i++) {
        if (data[i][0].toLowerCase() == str_upcoming) {
          Logger.log("true");
          rows.push(i);
        }
      }
  var row = Number(rows)+Number(rng.getRow());
  Logger.log(row);


}

Currently I am able to find the Header as well as getting the row number.

Hope you guys can understand.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Dr3am3rz
  • 523
  • 1
  • 13
  • 41

1 Answers1

2

Take a look at Faster way to find the first empty row; the answers there can be adapted to your situation.

The fastest solution there was Don Kirby's, and since you have a single column of data, it is ideal. We just need to change it to start searching from a particular headerRow!

/**
 * Search column A starting at the given row, to find
 * the first following empty row. Uses spreadsheet row numbers.
 * From: https://stackoverflow.com/a/38194740/1677912
 *
 * @param {Number} headerRow  Row number to start search at.
 *
 * @returns {Number}          Target empty row.
 */
function getFirstEmptyRowAfter(headerRow) {
  var spr = SpreadsheetApp.getActiveSpreadsheet();
  var column = spr.getRange('A:A');
  var values = column.getValues(); // get all data in one call
  var ct = headerRow;  // Start at row after headerRow (0-adjusted)
  while ( values[ct][0] != "" ) {
    ct++;
  }
  return (ct + 1);  // (1-adjusted)
}
Community
  • 1
  • 1
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
  • Thanks for the help! I did saw that answer though but somehow it did not work when I tried it. Will take a look at how to optimize the speed. – Dr3am3rz Jul 05 '16 at 03:48