简体   繁体   中英

Javascript - Looping through spreadsheet merged cells

I am looping through a range of data in a Google spreadsheet in JavaScript.

The problem I'm having is I have some merged cells that have the same value, for example C:6 to E:6 all have the same value as those 3 cells are merged.

So in my loop it will show C:6 = 'Focus and targeting' D:6 = '' and E:6 = '' What I'm trying to do is in my loop assign the 2nd and 3rd values to the first cell value.

Here is what I have:

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Audit');
  var range = sheet.getDataRange();
  var numRows = range.getNumRows();
  var numCols = sheet.getMaxColumns();
  var values = range.getValues();

  var count = 0;
  for (var i = 2; i <= numCols - 2; i++) {

    var questionCategory = values[5][i];


    if(questionCategory == undefined) {
      continue;
    }

    if(questionCategory == "") {
       // need to assign 2nd and 3rd cells of merged list to have the value of 1st cell in merged list     
    }

    count++;

  }

Here is what the data looks like:

在此处输入图片说明

Any ideas how I can achieve this?

Here is custom function to get merged cell value:

function getMergedCellValue(cellRange)
{
  if (!cellRange.isPartOfMerge())
  {
    return cellRange.getDisplayValue();
  }

  return cellRange.getMergedRanges()[0].getDisplayValue();
}

And updated code using this function:

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Audit');
  var range = sheet.getDataRange();
  var numRows = range.getNumRows();
  var numCols = range.getNumColumns();
  var values = range.getValues();

  var count = 0;
  var questionRowNum = 6;
  for (var i = 0; i < numCols; i++)
  {
    // assign 2nd and 3rd cells of merged list to have the value of 1st cell in merged list  
    var questionCategory = values[questionRowNum-1][i] || getMergedCellValue(sheet.getRange(questionRowNum, i+1));

    count++;
  }

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