使用Google Apps Script获取表格行列时getNextDataCell异常
问题解决:Google Apps Script 获取最后一列抛出异常
报错原因
getNextDataCell(SpreadsheetApp.Direction.RIGHT) 抛出异常的核心原因是:从A1单元格向右查找时,右侧没有可定位的非空单元格。该方法要求沿着指定方向必须存在至少一个后续非空单元格,否则会触发错误。而你获取last_row成功,是因为A列向下存在连续的非空数据。
解决方案
方案1:用try-catch捕获异常,处理无右侧数据的情况
通过异常捕获,当右侧无数据时直接将last_col设为A列的列号(1):
var ss = SpreadsheetApp.getActiveSpreadsheet() var sh = ss.getActiveSheet() let last_row = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow(); let last_col; try { last_col = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.RIGHT).getColumn(); } catch(e) { last_col = 1; }
方案2:改用更稳定的getLastColumn()方法
如果你的需求是获取工作表中所有有数据的最后一列(不要求和A1连续),直接使用工作表内置的getLastColumn()方法更可靠:
var ss = SpreadsheetApp.getActiveSpreadsheet() var sh = ss.getActiveSheet() let last_row = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow(); let last_col = sh.getLastColumn();
方案3:提前检查单元格数据,避免调用异常方法
先判断A1及右侧单元格是否有数据,再决定是否执行getNextDataCell:
var ss = SpreadsheetApp.getActiveSpreadsheet() var sh = ss.getActiveSheet() let last_row = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.DOWN).getRow(); let a1HasData = sh.getRange(1,1).getValue() !== ""; let nextColHasData = sh.getRange(1,2).getValue() !== ""; let last_col; if (a1HasData && nextColHasData) { last_col = sh.getRange(1,1).getNextDataCell(SpreadsheetApp.Direction.RIGHT).getColumn(); } else if (a1HasData) { last_col = 1; } else { // A1也无数据时,根据业务需求设置默认值,比如0 last_col = 0; }
内容的提问来源于stack exchange,提问作者K.Sugita
相关产品推荐
相关产品推荐

