VBA: For Each Cell in Range jumps out of range?

E

Ed

I have selected four cells in a single column and set a range to them. Then
I want to iterate through each cell of the range. The first pass works
fine, and affects the top cell of the selected cells. The next pass,
though, affects the cell to the right of the top cell, which is not supposed
to be included in the range! Why does this jump out of the range I've set?

Ed

Dim rng As Range
Dim cll As Cell
Set rng = Selection.Range
rng.HighlightColorIndex = wdBrightGreen
' Highlight affects only selected cells,
' indicating range is set properly.
For Each cll In rng.Cells
' Do Stuff
Next cll
 
J

Jay Freedman

Hi Ed,

I'm not sure where (if anywhere) this is documented, but you can't assign a
table column to a range. A Word range always starts in the first cell and
goes left to right to the end of the row, then to the first cell in the next
row and across -- just like the order you'd see if you tabbed from cell to
cell. The column of cells, if you could assign it, would be seen as a
discontinuous series of subranges, something VBA doesn't support. The user
interface does some magic to let you select a column, but VBA doesn't get
the use of that.

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the newsgroup so
all may benefit.
 
E

Ed

Thanks, Jay. Now I seem to remember being told that over a year ago, but
when you don't use it, you lose it.
I appreciate the boost.
Ed
 
H

Helmut Weber

Hi Ed,

Sub test099682()
Dim oCll As Cell
For Each oCll In Selection.Cells
oCll.Range.HighlightColorIndex = wdYellow
' there must be text in the cell to see the effect
Next
End Sub

Ranges in tables are tricky, complex, maybe buggy,
sometimes slower than the selection.

Select 2x2 cells somewhere in the middle of a larger table:

MsgBox Selection.Cells.Count
MsgBox Selection.Range.Cells.Count

--
Greetings from Bavaria, Germany

Helmut Weber, MVP WordVBA

Win XP, Office 2003
"red.sys" & Chr$(64) & "t-online.de"
 
E

Ed

Hi, Helmut. So maybe I shouldn't bother with a range object in this case
and just use Selection? That goes against almost everything you and Jay the
others have beat into me! <g> I'll remember that for next time. Thanks for
chiming in.
Ed
 
J

Jezebel

The key issue is that the cells collection belongs to a *table* --

For each pCell in Selection.Tables(1).Cells
...
 
T

Tony Jollans

Errm .. no it doesn't.

--
Enjoy,
Tony


Jezebel said:
The key issue is that the cells collection belongs to a *table* --

For each pCell in Selection.Tables(1).Cells
...
 

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