1
votes

I'm rather new to Google Apps Scripts and I wonder what the difference is between setting an active range and setting an active selection. As far as I understand, while I can set either the active range or the active selection in a sheet, I can get the active range only, but not the active selection. There is also a Range class with specific methods to operate on ranges, but no Selection class.

I have used both set methods,

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.setActiveRange(sheet.getRange("B5:H20"));

versus

sheet.setActiveSelection(sheet.getRange("B5:H20"));

but can see no difference in the web UI or the behavior.

The Google Apps Scripts documentation for the Sheets class says:

setActiveRange(Range)

Sets the active range for the active sheet.

Reference

setActiveSelection(Range)

Sets the active selection region for this sheet.

Reference

But I cannot find any information whether to use the one or the other, or which effect they have for the code or the users.

2

2 Answers

2
votes

Maybe this isn't the most helpful answer, but there may be a historical difference between the two methods that was removed. To further complicate things, there's also [range].activate()--what seems like just another way to accomplish the same thing. Hopefully that'll tide you over until someone more knowledgeable about the history of GAS comes along.

EDIT: By the way, I tested all three methods, and I can't discern any functional difference.

1
votes

This is an old post, but I had the same question so I thought I'd share the one difference I noticed (because it really confused me briefly when I was using setActiveRange() and setActiveSelection() interchangeably).

setActiveRange() takes only a range for input, while setActiveSelection() can take a range or an A1 notation string.

So if you want to set the cells in range A1:D4 to be active, with setActiveSelection you could write:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

sheet.setActiveSelection("A1:D4");

OR

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:D4");
sheet.setActiveSelection(range);

While with setActiveRange you would have to write that extra line in the second example:

var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];

var range = sheet.getRange("A1:D4");
sheet.setActiveRange(range);

(code from https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#setactiveselectionrange)

That's probably why they keep setActiveSelection around, as it simplifies things (by 1 line) under some circumstances.