Why does For Each over Range.Columns(1) not iterate over cells?

余生颓废 提交于 2021-02-04 21:12:08

问题


I can iterate over a range of cells to operate on each cell individually, if the range is specified by address:

Dim cell as Range
For Each cell In Range("A1:A10")
  debug.print cell.Address
Next cell

Produces the expected output:

$A$1
$A$2
... etc

But when I specify a column from the Columns collection of a range, iteration only runs once with the whole column:

For Each cell In UsedRange.Columns(1)
    Debug.Print cell.Address
Next cell

Produces just one output, with the whole column:

$A$1:$A$20

Is UsedRange.Columns(1) not a Range object? If not, what is it??

I've read this discussion of Rows/Columns as ranges and this on Range vs Range.Cells but I still can work out how to iterate over each cell in UsedRange.Columns(1).


回答1:


That is because a Column is a distinct Object itself. If you loop over columns, you loop one column at a time. To loop over the cells in a column:

Dim cell as Range
For Each cell In UsedRange.Columns(1).Cells
  debug.print cell.Address
Next cell


来源:https://stackoverflow.com/questions/55983823/why-does-for-each-over-range-columns1-not-iterate-over-cells

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!