Friday, December 9, 2011

Getting Table Cells Column by Column

Traversing a table's cells column by column is a little tricky due to the fact that there is no column object. The following algorithm does the job:
  1. Get the first row in the table using the Tbl property FirstRowInTbl.
  2. Get the first cell in that row using the Row property FirstCellInRow.
  3. While there are additional cells in the column, get the next cell in that column using the Cell property CellBelowInCol.
  4. While there are additional cells in the first row, get the next cell in that row using the NextCellInRow property. 
  5. Go to step 3.
This cell traversal pattern is illustrated below.
The following script traverses the selected table using this algorithm.

var doc, table, row, topRowCell, cell, cellNum = 0;

doc = app.ActiveDoc;
table = doc.SelectedTbl;
row = table.FirstRowInTbl;
if (row.ObjectValid()) { //get first row
    topRowCell = row.FirstCellInRow;
    while (topRowCell.ObjectValid()) {//traverse cells in first row
        cell = topRowCell;
        while (cell.ObjectValid()) { //traverse cells in column
            cellNum = cellNum + 1;
            var tLoc = new TextLoc();  //create text location object
            tLoc.obj = cell; //make it a cell
            tLoc.offset = 0; // insert at the start of the cell
            doc.AddText(tLoc, "Cell "  + cellNum);
            cell = cell.CellBelowInCol;
        topRowCell = topRowCell.NextCellInRow;
        cell = topRowCell;

An example of the output produced by this script is shown below.

No comments:

Post a Comment