Google-sheets – Iterating through a non-contiguous range in Google Spreadsheet

google sheetsgoogle-apps-script

Consider a Google Spreadsheet. Each row contains some measurement data from a given patient.

I wrote a Google Script function which iterates through the selected rows and exports each patient's data into a separate PDF file.

function Export() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("master-lab");
  var range = sheet.getActiveRange();
  var row0 = range.getRow();
  var row1 = row0 + range.getNumRows();
  for (i = row0; i < row1; ++i) {
    ExportRow(i);
  }
}

This code does not work if the user selects a non-contiguous array of rows, like in the following figure:

enter image description here

Is it there a way/workaround to iterate through non-contiguous ranges in Google Sheet?

Best Answer

The problem is not with iterating through ranges (having an array of ranges and an additional for loop to go over them is not a problem). The issue is the script will not know what the ranges are.

Google Apps Script is unable to access multiple ranges selected by a user. Only the last selected range is visible to it. There is a feature request Add support to allow use and manipulate disjoint Ranges which was filed in 2014 and remains outstanding.