简体   繁体   中英

Problems with arrays in Google Apps Script and Google Spreadsheet

Ok, the problem is that there is no way to set the range explictly without all the information on width and height. If I have 13 cells, why wouldn't it just write 13 cells? So, here is the script:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var targetSheet = ss.getSheetByName("Analytics");
  var entries = [{
    name : "Read Data",
    functionName : "readRows"
  }];
  ss.addMenu("Script Center Menu", entries);
  var rows = targetSheet.getDataRange();
  var numRows = rows.getNumRows();
  var values = rows.getValues();
  targetSheet.getRange(1,1,values.length,values[0].length).setValues(values);
  values[1] = readRows();
  rows.setValues(values);
};

readRows() returns the array of values. It worked with appendRow() but I can't find a way to override the second row in the table without all the complications. I tried everything. This way it keeps complaining about incorrect range height. Some other ways it even wrote the whole array to each cell of the row. I just can't get how this thing works. It seems absolutely illogical.

I mean I'm looking for something like setRow(2, readRows()) that will take exactly as many cells as there are values in the array and will override anything that have been written there before that, if any.

Ok, found the answer. It now looks this way:

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var targetSheet = ss.getSheetByName("Analytics");
  var array = [];
  var data = [];
  var entries = [{
    name : "Read Data",
    functionName : "readRows"
  }];
  ss.addMenu("Script Center Menu", entries);
  array = readRows();
  data[0]=array;
  var range = targetSheet.getRange('A2:M2');
  range.setValues(data);
};

The trick is to add the array to another array and achieve the two-dimensional array — the only format the setValues() and getValues() functions work with even if you want to modify a single line. It seems that there is no simpler option like setArray() or something like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM