user1592380
user1592380

Reputation: 36227

Get selected values in row

1

I want to be able to select a row and get the values in it. I have:

var id = ' ------gkqlDoUg'

 var sheet =    SpreadsheetApp.openById(id).getSheetByName('mysheeet')
 var vals= sheet.getActiveRange().getValues();

 Logger.log(vals)

when I run this there are no errors but I see:

[20-08-08 13:08:17:834 PDT] [[ ]]

How can I get this working?

Upvotes: 1

Views: 1897

Answers (3)

Wicket
Wicket

Reputation: 38160

There is something wrong, maybe a bug, but this fails randomly. Anyway here is a super simple demo of about "how to get this working"

  1. Create a spreadsheet
  2. Add some values to a row
  3. Select the row
  4. The following script to a bounded project to the previous spreadsheet
    function myFunction() {
      var values = SpreadsheetApp.getActiveRange().getValues();
      Logger.log(values);
    }
    
  5. Authorize the script
  6. Run the function.

[20-08-08 15:58:57:727 CDT] [[adfa, afdfafs, dasfasf, , , , , , , , , , , , , , , , , , , , , , , ]]


I think that there is a bug related to use chaining with getActiveRange().

This sometime fails to get the expected result

function myFunction2(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var values = sheet.getActiveRange().getValues();
  Logger.log(values);
}

NOTE: The following snapshots were taken from the script's executions page.

Failed
Fail

Succeded
Success

This gets the expected result

function myFunction3(){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  var range = sheet.getActiveRange();
  var values = range.getValues();
  Logger.log(values);
}

Related

The following are questions that uses Class Sheet getActiveRange() chained with some Class Range methods like getRow(), getValues() but the current answers doesn't mention the cause of the problem, they just offer an alternative code

Upvotes: 3

Marios
Marios

Reputation: 27348

You can select a specific row (in this case 68) as follows:

var sheet= SpreadsheetApp.getActive().getSheetByName('mysheeet')
var target_row = 68;
var vals= sheet.getRange(target_row,1,1,sheet.getMaxColumns()).getValues().flat([1]);

The flat() method can be omitted. I am using it in case you want the array to be 1 dimensional.


If you want to use getActiveRange() use SpreadsheetApp.getActive() instead :

var sheet =  SpreadsheetApp.getActive().getSheetByName('mysheeet')
var vals= sheet.getActiveRange().getValues();

and make sure that you select the entire row like you do in the screenshot. In your example, I think you are not referencing to the correct spreadsheet file.

Upvotes: 2

Cooper
Cooper

Reputation: 64040

Try:

Logger.log(vals[0].join(','));

Upvotes: 2

Related Questions