Referring to a table in VBA

P

Peter Rooney

Hello, Word VBA folk!

Please excuse me in advance for what must seem a daft question, but this is
the first time I've posted in Word VBA - I mostly do Excel and Project!

The ultimate aim of my code is to produce a checkerboard effect on any
table, so that, for example, cells on row 1 are black red, black re and on
row 2 are red black red black, and so on.

If anyone would like to help me with that, then great!

However, I was trying to produce a macro that would set all cells in the
table back to white, if my main code goofed up. Here is what I wrote:

Sub AReset()

ThisTable = ActiveDocument.Tables(1)
ColumnCount = ThisTable.Columns.Count
RowCount = ThisTable.Rows.Count

MsgBox (RowCount & " rows by " & ColumnCount & " columns")

For RowCounter = 1 To RowCount
For ColumnCounter = 1 To ColumnCount
MsgBox ("Row " & RowCounter & ", Column " & ColumnCounter)
'CellToColour = ActiveDocument.Tables(1).Cell(Row:=RowCounter,
Column:=ColumnCounter)
CellToColour = ThisTable.Cell(Row:=RowCounter,
Column:=ColumnCounter)
CellToColour.Shading.BackgroundPatternColorIndex = wdWhite
Next ColumnCounter
Next RowCounter

End Sub

I declared a variable "ThisTable" to refer to "activedocument.tables(1)"
The lines:

ColumnCount = ThisTable.Columns.Count
RowCount = ThisTable.Rows.Count

work fine, but when I tried:

CellToColour = ThisTable.Cell(Row:=RowCounter,
Column:=ColumnCounter)

I got "Object doesn't support this property or method"

although, obviously, if I replaced the offending line with:

CellToColour = ActiveDocument.Tables(1).Cell(Row:=RowCounter,
Column:=ColumnCounter)

this worked OK. It's only a small point, but it seems a bit unwieldy to have
to keep referring to a table in this longhanded way. Can anyone help?

Cheers

Pete
 
M

Martin Seelhofer

Hey Peter

Sometimes, a tiny little omission can lead to a totally different
interpretation by the VBA-Interpreter ;-)

In your code, you write
ThisTable = ActiveDocument.Tables(1)

However, since you want to refer to the table *object*, you
must write:

Set ThisTable = ActiveDocument.Tables(1)


NB: You would have noticed this problem, if you would have
turned on Option Explicit and appropriately declared ThisTable
as of type Table ;-)


Cheers,
Martin
 
P

Peter Rooney

Martin,

Thanks very much for this - I forgot my "set" !

Just as a matter of interest, what variable type should I use for "ThisTable"

It's currently set as string, but I thought a table should be an object..?
Both work.

I worked out my code for checkerboarding the table, by the way! :)

Cheers

Pete
 

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

Top