Cycle through table rows with a for statement

  • Thread starter Vincent Boris Arnold
  • Start date
V

Vincent Boris Arnold

I want to cycle through the rows of a Word table in order
to change the font characteristics of the cells. There is
a separate font change I want to do for the first
(heading) row of the table. The statements I've coded are
below. When I execute this code, I get a "Type mismatch"
(Run-time error '13') message on the second statement.


For Each vRow In vSysInterfaceTable.Rows
For Each vCell In vSysInterfaceTable.Rows(vRow).Cells
vCell.Select
Selection.Font.Size = 9
If vRow = 1 Then
Selection.Font.SmallCaps = True
End If
Next vCell
Next vRow
 
J

Jay Freedman

Hi Vincent

The argument of the .Rows() method must be an integer index between 1 and
vSysInterfaceTable.Rows.Count, but you're trying to use a Cell object (or a
Variant containing a Cell object).

You can either change the first statement of your code to

For vRow = 1 to vSysInterfaceTable.Rows.Count

and it would also be a good idea to declare the variable explicitly with Dim
vRow As Integer. You should also declare

Dim vSysInterfaceTable As Table
Dim vCell As Cell

Finally, two bits of extra advice:

1. Don't select things in order to change their formatting or to do other
things to them. It just slows down the macro -- very significantly if the
document is large. Instead, use the properties of the .Range property like
this:

Dim vSysInterfaceTable As Table
Dim vRow As Integer
Dim vCell As Cell

Set vSysInterfaceTable = ActiveDocument.Tables(1)
For vRow = 1 To vSysInterfaceTable.Rows.Count
For Each vCell In vSysInterfaceTable.Rows(vRow).Cells
vCell.Range.Font.Size = 9
If vRow = 1 Then
vCell.Range.Font.SmallCaps = True
End If
Next vCell
Next vRow

2. Whenever possible, don't apply direct formatting at all, even with a
macro. It just makes the document much harder to maintain. Instead, use
styles. Create a special style for the first row that includes the 9 pt size
and the small caps, and another style for the other rows that includes just
the size. You can apply the styles through the toolbar dropdown (or task
pane or Format > Style dialog), or you can apply them with a macro. You can
also format an empty table and store it as an AutoText entry, which you can
use to create new tables that are already formatted.
 
K

Klaus Linke

Hi Vincent,

Replace the second line with
For each vCell in vRow.Range.Cells

Regards,
Klaus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top