Friday, 14 December 2018

Get ActiveCell

The following Google Apps Script code is a very basic introduction to scripting in Google Sheets and formed the first function I created. It works by getting the value and row number of the selected cell in the active spreadsheet, which you could then use in another function.

The code starts by getting the current active spreadsheet and sheet (so this will vary depending on where you are clicked when you run the function - rather than specifying an exact sheet to access). From here the 'activeCell' is acquired (so where the cursor is clicked on the sheet), then the value ('getValue') of that cell is captured in a variable and logged for reference. Finally it looks for the row number ('getRow') of the current cell and logs that too.

function getActiveCell() {
// get the active spreadsheet and sheet
var ss = SpreadsheetApp.getActiveSpreadsheet(); // ss contains entire spreadsheet
var sheet = ss.getActiveSheet(); // sheet contains current active sheet ('Students')
// from sheet, get active cell and store as variable
var activeCell = sheet.getActiveCell();
// from activeCell, get value and store as variable
var cellValue = activeCell.getValue();
// show value of cellValue
Logger.log(cellValue);
// from activeCell, also show row number
var cellRow = activeCell.getRow();
Logger.log(cellRow);
}
Get ActiveCell.xlsx

2 comments: