1

I have some Google Apps Script code which works with Google Sheets. In one segment of code there are some instances where it throws an exception.

Here is the exception:

Exception: Cell reference out of range

Here is the line of code (and the one preceding it) that is throwing the exception:

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Reservations');
  var cell = sheet.getActiveCell(); // This is where the exception is thrown

This error happens but not consistently. What I want to do is check if sheet.getActiveCell() is pointing to a reference out of range or if it is returning a valid value. If it is pointing to a reference that is out of range I would like to set the value of cell to an alternative value.

How do I check if sheet.getActiveCell() is returning a value that is in range?

3

If you can use getCurrentCell, then instead of throwing an exception, it returns null if there is no active cell. There are some difference between the getCurrentCell and getActiveCell though.

With getCurrentCell, you can do this:

 var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Reservations');
 var cell = sheet.getCurrentCell();
 if(cell) {
   // Rest of your code that needs access to the active cell
 } else {
   // There is no active cell, do something else
 }

If you can't use getCurrentCell, then you can use a try-catch block to catch the exception.

 var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Reservations');
 try {
   var cell = sheet.getActiveCell();
   // Rest of your code that needs access to the active cell
 } catch (e) {
   // There is no active cell, do something else
 }
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.