What's the difference between getActiveCell and getCurrentCell in Google Apps Script?
Asked Answered
M

1

9

I've read the definitions a few times over and I still don't understand the difference.

getActiveCell: Range

getCurrentCell: Range

  • https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getCurrentCell()
  • Summary: Returns the current cell in the active sheet or null if there is no current cell.
  • Description: Returns the current cell in the active sheet or null if there is no current cell. The current cell is the cell that has focus in the Google Sheets UI, and is highlighted by a dark border. There is never more than one current cell. When a user selects one or more cell ranges, one of the cells in the selection is the current cell.

There's this note in getActiveCell's documentation: (copy-pasted including grammatical errors)

It's preferrable to use getCurrentCell(), which the returns the current highlighted cell.

Which doesn't make it any clearer

Madelynmademoiselle answered 20/5, 2020 at 5:48 Comment(2)
I think that both methods returns the same values and can be used for the same way. The difference might be the following points. The method of getActiveCell() in Class Sheet and Class Spreadsheet had added before 2010. The method of getCurrentCell() in Class Sheet and Class Spreadsheet has been added at April 11, 2018. From this, the internal scripts for each method might be difference.Distributor
@Distributor They are not quite the same. If you have a selected range, then depending on how the range has been selected, getActiveCell() and getCurrentCell() will return different ranges.Tunnel
T
25

Answer:

getCurrentCell() returns the highlighted cell as seen by the dark border in the Sheets UI, whereas getActiveCell() returns the top-left cell of the selected range.

Example:

Say you have a range highlighted in a Sheet: B2:E10, for example. In the case where the you clicked on B2 and dragged down to E10:

enter image description here

Running the following code in the script editor:

function getCells() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1")
  console.log(sheet.getActiveCell().getA1Notation())
  console.log(sheet.getCurrentCell().getA1Notation())
}

You will see in the logs that both getActiveCell() and getCurrentCell() return B2.

However in the opposite scenario, where you clicked on E10 and dragged up to B2:

enter image description here

After running the same code, you will see that getActiveCell() still returns B2, but now getCurrentCell() returns E10.

Tunnel answered 20/5, 2020 at 14:47 Comment(1)
If called from a custom function, both seem to return the cell that the function was called from. Can anyone comment on this? @Tanaike?Jameljamerson

© 2022 - 2024 — McMap. All rights reserved.