Reputation: 3198
I have a google sheet where i need to merge the cells if the values are repeating
The expected is to merge the cell from A1 to A4 and have a single value A in it.
I have tried with,
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getActiveRange();
//var values = range.getValues();
var numCols = values[0].length;
values = [
["A", "B", "C", "D", "E"],
["A", "B", "S", "D", "E"],
["A", "D", "C", "D", "E"],
["A", "B", "C", "D", "K"],
["c", "B", "W", "D", "K"],
["A", "B", "C", "D", "E"],
]
for (var j = 0; j < numCols; j++) {
var placer = '';
for (var i = 0; i < values.length - 1; i++) {
if (values[i][j] == values[i + 1][j])
range.getCell(i + 2, j + 1).setValue('');
}
}
Upvotes: 0
Views: 269
Reputation: 201438
You want to achieve the following situation.
If my understanding is correct, how about this modification? Please think of this as just one of several answers.
The flow of my sample script is as follows.
// Retrieve values from the active sheet.
var sheet = SpreadsheetApp.getActiveSheet();
var values = sheet.getDataRange().getValues();
// Transpose values.
var res1 = values[0].map(function(_, i) {return values.map(function(e) {return e[i]})});
// Merge cells.
res1.forEach(function(col, i) {
var temp = {};
col.forEach(function(row, j) {
if (row === col[j + 1] && !(row in temp)) {
temp[row] = j;
} else if (row != col[j + 1] && row in temp) {
sheet.getRange(temp[row] + 1, i + 1, (j - temp[row]) + 1, 1).merge();
temp = {};
}
});
});
If I misunderstood your question and this was not the result you want, I apologize.
This is the answer for the additional question.
// Retrieve values from the active sheet.
var range = SpreadsheetApp.getSelection().getActiveRange();
var sheet = range.getSheet();
var values = range.getValues();
// Transpose values.
var res1 = values[0].map(function(_, i) {return values.map(function(e) {return e[i]})});
// Offset
var r = range.getRow() - 1;
var c = range.getColumn() - 1;
// Merge cells.
res1.forEach(function(col, i) {
var temp = {};
col.forEach(function(row, j) {
if (row === col[j + 1] && !(row in temp) && row != "") {
temp[row] = j;
} else if (row != col[j + 1] && row in temp) {
sheet.getRange(r + temp[row] + 1, c + i + 1, (j - temp[row]) + 1, 1).merge();
temp = {};
}
});
});
Upvotes: 2