How to define the range as the 'selected field'?

151 Views Asked by At

I'm new at coding and I'm looking for the accurate syntax to define the range as the selected field.

I created a macro to change the color of the field (here for the color 'red'). I can do it on a defined field such as 'A1' or a group of fields such as'A1:Z40'.

But I tried to search for the right syntax if I want this macro works only for the current selected field.

What should I type instead of 'A1'?

function Rouge() {   
  var spreadsheet = SpreadsheetApp.getActive();  
  spreadsheet.getRange('**A1**').activate();  
  spreadsheet.getActiveRangeList().setBackground('#ff0000');
}
2

There are 2 best solutions below

0
On

If you will be using a spreadsheet you should know that spreadsheets have sheets, cells, ranges, rows and columns among other concepts but there aren't fields. This specially relevant in order to be able to find the information that you need on the official reference.

Regarding how to get something that could be similar to getting the "selected field", see

0
On

There's no A1-notation syntax for specifying the currently selected ranges because, by definition, it's not something that can be specified beforehand.

The value returned by Spreadsheet.GetActiveRangeList() will facilitate manipulating all of the cells that are currently selected.

function setActiveRangesBackground() {
  var activeRangeList = SpreadsheetApp.getActiveRangeList();
  if (activeRangeList !== null) {
    activeRangeList.setBackground("#000000");
  }
}

Similarly, if you only want to manipulate the currently selected cell (i.e. the one with the dark border around it) you use Spreadsheet.getCurrentCell().

function setCurrentCellBackground() {
  var currentCell = SpreadsheetApp.getCurrentCell();
  if (currentCell !== null) {
    currentCell.setBackground("#000000");
  }
}