Get last row of specific column function - best solution

試著忘記壹切 提交于 2019-12-04 19:18:13

There's only one minor mistake on your code, you should use the === operator and not the ==. Because you're considering "0" values as empty. If you don't know the difference between them, try a quick search to learn more.

It's weird though that you named the variable that holds the column number as "RowNumber", why not "columnNumber"? It makes more sense to me.

Another thing that I usually try to do on all my scripts is to reduce API calls. And it's very common that after searching I'll need the data elsewhere. So, it would be good if this function accepted the data directly instead of the sheet object. Or maybe either one.

At last, it probably does not really make a big difference, but you could do one less subtraction per loop, by starting one less.

Putting my comments to practice, here's the resulting code:

function getLastRowOfColumn(columnNumber, optData, optSheet) {
  var data = optData !== null ? optData : optSheet.getDataRange().getValues();
  var row = data.length-1;
  for( ; row > 0 && data[row][columnNumber] === ''; --row ) ;
  return row+1;
}

A caveat on both our codes, we're considering blank just by checking a cell value. It might have a formula, which by definition means that the cell is not blank, that is returning an empty string. e.g.

=IF(A1="Some comparison that returns false"; "really?"; "")

There are faster ways to do it and consuming less api data: 1) you can use binary search instead of looping potentially all rows. Make sure there are no holes in your column for that to work. 2) you can get just the column instead of the entire range by doing getRange ("a1:a") however you wi need to construct that range string based on the column you want

You can combine 1 & 2 Cheers

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