How to get the current active sheet in my script?

I created from scratch a brand new spreadsheet, within which, I created a few tabs/sheets with some data within each; and then in google apps script in that spreadsheet I installed the following code:

function getCurrentRow() {
  var currentSelection = SpreadsheetApp.getActiveSheet().getActiveSelection()
  var currentValue = currentSelection.getValue();
  var currentRow = currentSelection.getRowIndex();
  Logger.log(currentValue);
  Logger.log(currentRow);

  return currentRow;
}

I ran the script, and it gave me the correct results for the sheet that was open/which cell was selected. So I would say that this code pretty much works as you expect.

In your case, may I suggest that the quickest way to get more info about the error, or to see if the error persists, is for you start from scratch too, with a new spreadsheet, and paste in the code above, and then test to prove that at least that much works for you too. Then, only after this, paste in the greater code (that you have linked to), and see if it still/stops working.


I'm having the same problem while developing in the Script Editor -- the Script Editor instance/window becomes 'disconnected' from the Sheets instance/window and just has the first sheet / A1 etc as the 'actives'.

What worked for me:

Closing the Script Editor window and re-opening from Sheet > Tools > Script editor. Voila, .getActive...()s are working again.

Also:

As implied by some of the other answers, triggering the execution from the Sheets window/instance (probably always) also works. One of the answers calls a function from a cell, which means it's going to be triggered by the Sheet. Another option would be to add a .UI menu and menu-option and trigger it there.