How to get ColumnIndex value in VBA when navigating in a Word Table RRS feed

  • Question

  • Hi,

    I have a Word document with tables, and I ask via VBA to go through table 4 from top to bottom in column 4. What I want to know is the ColumnIndex of the cell in which is located the cursor (and store it in a variable called NumCol). Based on that information an action is required (color cell in column 5). When the answer is 1 (only one cell in the row; merged cells) then skip this row and go to next row.

    But I constantly get compile errors when using instructions as : NumCol=ActiveDocument.Tables(4).cell.ColumnIndex . Same error when I ask for the number of columns in a row, or the number of cells.

    Where could be my error ?


    Wednesday, April 16, 2014 3:51 PM


  • Since you refer to the column the cursor is in, that implies you're working with a Selection. In that case, the retrieving the column index requires nothing more than Selection.Cells(1).ColumnIndex.

    However, your mention of using VBA to go through the table from top to bottom suggests you may be working with range objects. Without knowing how you're doing that, it's difficult to give specific advice. However, the following will shade any cell in column 5 whose 'value' in table 4 is 1:

    Dim TblCell As Cell, Rng As Range
    For Each TblCell In ActiveDocument.Tables(4).Range.Cells
      If TblCell.ColumnIndex = 5 Then
        Set Rng = TblCell.Range
        With Rng
          .End = .End - 1
          If .Text = "1" Then
            TblCell.Shading.BackgroundPatternColorIndex = wdYellow
          End If
        End With
      End If

    Paul Edstein
    [MS MVP - Word]

    Thursday, April 17, 2014 1:51 AM