获取特定列函数的最后一行 - 最佳解决方案 [英] Get last row of specific column function - best solution

查看:19
本文介绍了获取特定列函数的最后一行 - 最佳解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

With "lastRow" one can get the last row in a sheet. Sometimes you need the last row of a specific column. Google Apps script das not provide this function. There are around 5 questions and solutions already here on the site, but all have some specific code wrapped around it.

I took the solution what i think is the fastest in most cases - you start looking at the end of the sheet and look backwards in the column you specified - and made a clean function out of it.

So this is a contribution for beginners to copy paste this - the argument "RowNumber" is the column you want to look at as a number: 0 is A, 1 is B, 2 is C etc. The function returns the last row as a number ("4")

Because i am on day 3 as a apps script user, my question is: if this is not the fastest and cleanest way to do it, or the script does not work properly on some circumstances, please tell me. for my usecase it works perfect.

function getLastColumnRow(RowNumber, sheet) {
  var data = sheet.getDataRange().getValues();
  var numRows = data.length;

 // loop from bottom to top for last row in given row "RowNumber"
  while( data[numRows - 1][RowNumber] == "" && numRows > 0 ) {
    numRows--;
  }
  return numRows
}

解决方案

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

这篇关于获取特定列函数的最后一行 - 最佳解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆