2

This should be a simple one, but I could not crack it myself... I want to copy the currently selected cells in the active sheet in an array called data:

var sheet = SpreadsheetApp.getActive().getActiveSheet();
var selection = sheet.getActiveRange();
var data = selection.getValues();

The above results in the array getting the content of cell A1, no matter which cells are actually selected. When I replace getActiveRange() with e.g. getRange(2,1,10,10) that works as expected.

Any clue as to why I cannot get to the currently selected cells is appreciated!

user3288616
  • 41
  • 1
  • 4

3 Answers3

2

I think that the problem is

var sheet = SpreadsheetApp.getActive().getActiveSheet();

This because there is some kind of bug when "chaining" methods of two different Object Classes, in this case Class Spreadsheet and Class Sheet. There is a bug report related to this getActiveSheet() returns first sheet name

The workaround is to replace the above line with:

var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getActiveSheet();

Related

Rubén
  • 34,714
  • 9
  • 70
  • 166
2

It looks like the problem was on Google's side because after 24 hours of failure the existing code now works flawlessly. All your versions work fine too now.

user3288616
  • 41
  • 1
  • 4
  • 2
    Today the same code does not work... that is: it does not work in Chrome. I fired up Internet Explorer and it works there! Quite scary to see that your Google scripts might work or fail based on the browser you are using, and that Google's own browser fails! – user3288616 Jan 07 '19 at 22:49
0

This gets and displays the active range in a dialog window.

function getARange(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getActiveSheet();
  var rg=sh.getActiveRange();
  var vA=rg.getValues();
  var s='';
  for(var i=0;i<vA.length;i++){
    s+=Utilities.formatString('<br />%s', vA[i].join(','));
  }
  var userInterface=HtmlService.createHtmlOutput(s);
  SpreadsheetApp.getUi().showModelessDialog(userInterface, 'The Active Range')
}
Cooper
  • 59,616
  • 6
  • 23
  • 54
  • Thanks for the effort! But that does not work here either, did you test it? It never gets to showing the dialog. Logging vA shows it to contain the cell A1 (the range is probably undefined?). Could the issue be something other than the code? I run it straight from code editor... – user3288616 Jan 04 '19 at 10:08
  • I’m guessing that you realize that you have to go back to the spreadsheet to see the dialog. I only bring this up because some people have neglected to do that in the past. – Cooper Jan 04 '19 at 14:34