Last active
June 12, 2025 12:31
-
-
Save tallcoleman/777b4bc2304fb1a2b7996217893584b8 to your computer and use it in GitHub Desktop.
Intersect() function for Google Apps Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns the intersection of two ranges, or null if there is no overlap. | |
* @param {SpreadsheetApp.Range} r1 Range 1 | |
* @param {SpreadsheetApp.Range} r2 Range 2 | |
* @returns {SpreadsheetApp.Range} | |
*/ | |
function Intersect(r1, r2) { | |
if (r1.getSheet().getSheetId() !== r2.getSheet().getSheetId()) return null; | |
const FIRSTROW = Math.max(r1.getRow(), r2.getRow()); | |
const LASTROW = Math.min(r1.getLastRow(), r2.getLastRow()); | |
const FIRSTCOL = Math.max(r1.getColumn(), r2.getColumn()); | |
const LASTCOL = Math.min(r1.getLastColumn(), r2.getLastColumn()); | |
if (FIRSTROW > LASTROW || FIRSTCOL > LASTCOL) return null; | |
return r1.getSheet().getRange(FIRSTROW, FIRSTCOL, LASTROW - FIRSTROW + 1, LASTCOL - FIRSTCOL + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!
This JSDoc will work with the online editor, so the results get the appropriate code hints: