Skip to content

Instantly share code, notes, and snippets.

@tallcoleman
Last active June 12, 2025 12:31
Show Gist options
  • Save tallcoleman/777b4bc2304fb1a2b7996217893584b8 to your computer and use it in GitHub Desktop.
Save tallcoleman/777b4bc2304fb1a2b7996217893584b8 to your computer and use it in GitHub Desktop.
Intersect() function for Google Apps Script
/**
* 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);
}
@Black-Platypus
Copy link

Thank you!
This JSDoc will work with the online editor, so the results get the appropriate code hints:

/**
 * 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}
*/

@tallcoleman
Copy link
Author

@Black-Platypus thanks - have updated!

@Black-Platypus
Copy link

Wow! Did not expect such a quick response (or any)! ๐Ÿ˜Š๐Ÿ™Œ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment