Skip to content Skip to sidebar Skip to footer

Is There An Existing Way In Google Script To Check If An A1 Notation Is In Range Of A Second A1 Notation

I am currently writing a function for this myself, could not find an existing function in the google docs. But I was wondering, this is so standard, there should be a default way t

Solution 1:

We can use regex to separate strings and test them individually. Try this sample:

/**
 * @return {boolean} Returns TRUE If the given a1Notation is in the rangeToCheck
 * @param {"A1"} a1Notation The range in A1Notation
 * @param {"A1:B1"} rangeToCheck The range in which to check the A1 Notation
 */functionwithinRange(a1Notation, rangeToCheck) {
  var input = Array.prototype.map.call(arguments, function(e) {
    return e.toUpperCase();
  });
  var rangeArgs = /^([A-Z]+)?(\d+)?:([A-Z]+)?(\d+)?$/.exec(input[1]);
  var a1NotationArgs = /^([A-Z]+)(\d+)$/.exec(input[0]).map(function(e, i) {
    return i == 1 ? ('  ' + e).substr(-2) : e * 1;
  });
   /* If range arguments are missing(like missing end column in "A1:1"), add arbitrary arguments(like "A1:ZZ1")*/
  rangeArgs = rangeArgs.map(function(e, i) {
    return e === undefined ?
      i % 2 === 0 ?
        i > 2 ?
          Infinity : -Infinity
        : i > 2 ?
          'ZZ' : ' A'
      : i % 2 === 0 ?
        e * 1 : ('  ' + e).substr(-2);
  });
  console.log(rangeArgs, a1NotationArgs);
  return (a1NotationArgs[1] >= rangeArgs[1] &&
    a1NotationArgs[1] <= rangeArgs[3] &&
    a1NotationArgs[2] >= rangeArgs[2] &&
    a1NotationArgs[2] <= rangeArgs[4]);
}

The above supports up to 2 letter columns.

Solution 2:

There are probably some issues with this code, but maybe it will give you an idea.

functionisWithinA1Range(a1Notation,a1_Two) {
  var columnRangeOneStart,colmRngOneEnd,columnRange2Start,colmRng2End,columnIsInside,
      rng,rng2,sh,ss;

  ss = SpreadsheetApp.getActiveSpreadsheet();
  sh = ss.getActiveSheet();

  rng = sh.getRange(a1Notation);
  rng2 = sh.getRange(a1_Two);

  columnRangeOneStart = rng.getColumn();
  colmRngOneEnd = rng.getLastColumn();

  columnRange2Start = rng2.getColumn();
  colmRng2End = rng2.getLastColumn();

  columnIsInside = columnRangeOneStart >= columnRange2Start && columnRangeOneStart <= colmRng2End;

  rowRangeOneStart = rng.getRow();
  rowRngOneEnd = rng.getLastRow();

  rowRange2Start = rng2.getRow();
  rowRng2End = rng2.getLastRow();

  rowIsInside = rowRangeOneStart >= rowRange2Start && rowRangeOneStart <= rowRng2End;

  if (columnIsInside && rowIsInside) {

    returntrue;
  }
}

Post a Comment for "Is There An Existing Way In Google Script To Check If An A1 Notation Is In Range Of A Second A1 Notation"