问题
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