Merge table cells with a script
Hi all
I've written the following script:
function _table() {
if (app.selection.length > 0) {
var _selection = app.selection[0];
if (_selection.parent.constructor.name == "Table" || _selection.parent.parent.constructor.name == "Table") {
var _cells = _selection.columns[0].cells;
for (var i = 0; i < _cells.length - 1; i++) {
var i2 = i + 1;
if (_cells[i].contents === _cells[i2].contents) {
var _mergeValue = _cells[i].contents;
_cells[i].merge(_cells[i2]);
_cells[i].contents = _mergeValue;
if (_cells[i].contents === _cells[i2].contents) {
i--;
}
}
}
}
}
}
app.doScript(_table, ScriptLanguage.JAVASCRIPT, [], UndoModes.ENTIRE_SCRIPT);
Unfortunately it's not performing as expected. What it should do is loop through the selected cells and check if subsequent cells contain the same content and merge them if they do. And not only merge them but only keep one instance of the content, not both, as would be standard with InDesign.
In some cases, this works fine. In some, it behaves weirdly and in some cases it doesn't work at all.

In this case, it works on one of the columns. If I select the other one, the script doesn't do anything. It doesn't matter which column I start with.

In this case, it behaves completely unexpectedly. It merges some of the cells but not correctly. This is the result:

Any ideas why the script behaves like that? Any help is much appreciated!