Google Apps Script中Range.getHeight()与getNumRows()的区别是什么?
Range.getHeight() and Range.getNumRows() Great question! Let's break down what these two methods do, how they overlap, and where they might differ based on the official docs and your test findings.
What Each Method Does (Per Official Documentation)
getNumRows(): This method’s sole job is to return the number of rows in your specified range as an integer. Here’s how it works in practice:var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D5"); Logger.log(range.getNumRows()); // Logs 4, since rows 2 to 5 add up to 4 rowsgetHeight(): This method returns the height of the range as an integer. From the example provided:var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var range = sheet.getRange("B2:D4"); Logger.log(range.getHeight()); // Logs 3.0, which matches the number of rows in this range
Your Test Results
When you ran the diffTest() function, both methods spit out the same value (26) every time — whether you used a programmatically defined range or a named range. You also ruled out two potential variables:
- Manually changing the actual height of cells in the range didn’t affect the output
- Line breaks inside cells also had no impact on the results
So, Are There Any Differences?
Even though your tests showed identical results, the core intent of each method sets them apart:
getNumRows()is explicitly built to count rows — it will always return the exact number of rows in your range, no exceptions. This is its dedicated purpose, so it’s the most reliable choice if you need a row count.getHeight()is meant to report the range’s physical height dimension. Your tests show it matching the row count, but this might be a coincidence in your setup (like using uniform default row heights). That said, your observation that modifying cell heights didn’t change the output is interesting — it suggests that in some contexts,getHeight()might return the row count instead of pixel-based height, but the official docs frame it as a height-focused method.
If your goal is to get the number of rows, stick with getNumRows() for clarity and consistency. Use getHeight() only if you’re specifically concerned with the range’s physical height (even if in your tests it aligned with row count).
内容的提问来源于stack exchange,提问作者Rafa Guillermo

