google-apps-scriptgoogle-sheetsreturn-valuegoogle-apps-script-editorgetvalue

I want to get the values of a row of a spreadsheet based on the selected cell


I need to get all values of a row of a spreadsheet based on the cell that I have selected. Example: I have selected the Cell F1. Now I want the all value in that row (for example F1, F2, F3, F4, F5).

What I tried:

  var selection = SpreadsheetApp.getActiveSheet().getSelection()

  var val1 = selection.getValue()
  var val2 = values.getNextDataRange(SpreadsheetApp.Direction.NEXT).getValue()
  var val3 = values.getNextDataRange(SpreadsheetApp.Direction.NEXT).getValue()
  ...

Then I thought I could selection the whole row in which I am interested so that I have a list of all values that I could get with xy[0], xy[1], xy[2]... but that was not succesful.

  var values = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data').getSelection().getActiveRange();
  
  var val1 = values[0]
  var val2 = values[1]
  ...
  var values = SpreadsheetApp.getActive().getActiveRange().getA1Notation();
  var val1 = values[0]
  var val2 = values[1]
  ...

My last idea was to get just the position of the selected cell, e.g. F1. Thus I could get all values directly:

  var value1 = SpreadsheetApp.getActiveSheet().getRange(5, 0).getValue();
  var value1 = SpreadsheetApp.getActiveSheet().getRange(5, 1).getValue();
  var value1 = SpreadsheetApp.getActiveSheet().getRange(5, 2).getValue();
  ...

Unfortunately nothing worked so far. Has someone a solution to my problem?


Solution

  • Assuming that you actually want to retrieve the values in the selected row, and not column (so, if F1 is selected, you want to retrieve A1, B1, C1, etc., not F1, F2, F3, etc., you can just do this:

    Code sample:

    function getRowValues() {
      var sheet = SpreadsheetApp.getActiveSheet();
      var rowIndex = sheet.getCurrentCell().getRow();
      var rowValues = sheet.getRange(rowIndex, 1, 1, sheet.getLastColumn()).getValues()[0];
      return rowValues;
    }