Google Spreadsheet script to merge cells in column

2020-07-10 11:23发布

I'm trying to merge cells containing a certain word in column A (e.g. 'Hello') with the cell to the immediate right (in column B)

E.g. A4 = 'Hello', therefore I would like to merge cells A4 and B4.

I have this code so far:

function formatCells() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var s = ss.getSheetByName('Combined');
  var range = s.getDataRange()
  var values = range.getValues();

  for( var row = values.length -1; row >= 0; --row )
    if (values[row][1] == 'Hello')
      {s.getRange(row+1,1).mergeAcross();
}
}

But the code doesn't seem to be doing anything at all? Can anyone out there kindly tell me what I'm doing wrong?

Many thanks for looking.

1条回答
爷的心禁止访问
2楼-- · 2020-07-10 11:54

Arrays are 0 indexed,so column A is index 0... You should simply use values[row][0] in your condition.

And to mergeAcross two cells you'll need to get a 2 cells range like this :

s.getRange(row+1,1,1,2).mergeAcross();

Note also that you will loose the value that was in column B since the merge method doesn't merge contents. I don't know if thar's an issue for you...

查看更多
登录 后发表回答