Question

I needed a script that will merge any empty cells in a table in an InDesign document with the cell directly above it. I thought I had it figured out, with this script:

var myDoc = app.activeDocument;

myPage = myDoc.pages;

for (var p=0; myPage.length>p; p++){

    try{

var myTable = myPage[p].textFrames.everyItem().tables.everyItem();

if (myTable.constructor.name == 'Table'){

for (var t = myTable.cells.length - 1; t >= 0; t--)
            {

           if (myTable.cells[t].contents==""){
              var w = myTable.columns.length;
               myTable.cells[t-w].merge(myTable.cells[t]);

               }

            }

        }

    }

  catch(e){}

}

which worked great, until I tried it on a document with more than one table on the same page, in which case it does nothing to any of the tables on that page, which is unfortunate, because the tables I need this script for are on the same page.

Was it helpful?

Solution

The everyItem() function returns a collection of items. you need to loop them as well.

var myDoc = app.activeDocument;
// loop pages
for (var p = 0; myDoc.pages.length > p; p++) {
  var onepage = myDoc.pages[p];
  // loop textframes
  for (var tf = 0; tf < onepage.textFrames.length; tf++) {
    var onetf = onepage.textFrames[tf];
    // loop tables
    for (var tb = 0; tb < onetf.tables.length; tb++) {
      var onetable = onetf.tables[tb];
      // loop cells
      for (var t = onetable.cells.length - 1; t >= 0; t--) {
        if (onetable.cells[t].contents === "") {
          var w = onetable.columns.length;
          onetable.cells[t - w].merge(onetable.cells[t]);
        }
      }
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top