Good day everyone!
I'd like to have a function similiar to VBA's intersect
in Google Sheets Script. Is there a nifty way to do this? The function must return:
RangeIntersect(R1, R2) = true
if R1 has common cells with R2,RangeIntersect(R1, R2) = false
if R1 has no common cell with R2
Thank you in advance.
Speed test
I want the function to work as fast as possible. That's because it would be used in loops inside onEdit
function. If you like, test provided function with this script:
function speedtest () {
var sheet;
sheet = SpreadsheetApp.getActiveSheet();
var rr1 = ['A1:C16', 'B2:B88', 'D1:D8', 'E1:E17', 'A18:B51', 'A13:A14', 'A17:C17'];
var r1, r2;
r1 = sheet.getRange(rr1[0]);
var rr2 = [];
// define some ranges
for (var x = 0; x < 30; x++) {
for (var i = 0; i < rr1.length; i++) {
r2 = sheet.getRange(rr1[i]);
rr2.push(r2);
}
}
var C;
var start, end, time;
// timer start
for (var t = 0; t < 10; t++) {
start = new Date().getTime();
for (var f = 0; f < rr2.length; f++) {
C = RangeIntersect(r1, rr2[f]);
}
end = new Date().getTime();
time = end - start;
Logger.log('Execution time = ' + time);
}
}
First, you will need to get your range coordinates:
Second, you will need to know if the column bounds and row bounds overlap:
Your requested function to compare two ranges:
And here's a quick test:
Please note that this is just a quick solution. Also note that getActiveRange will include any rows and columns hidden through hide or filtering and would otherwise be included in the selected range.
Added 2016-05-04
A shortened version of Max's quicker solution with a single return (I prefer a single exit point):
If you want the range representing the intersection you can use the following code:
I've made my own version of this script:
This script works ~1.4 times faster because it returns each time when 2 ranges don't intersect.