How to iterate through a variable-column-length range in Excel using VBA

匿名 (未验证) 提交于 2019-12-03 00:44:02

问题:

For example, if the data in one worksheet looks like:

UsedRange.Columns.Count is 6 which is the maximum column count for all rows. Even if I iterate using

For each row in UsedRange.Rows        For each cell in row.Cells            ...        Next cell Next row 

It's still counting 6 for each row.

回答1:

Just exit your cell loop if the cell is Empty.

For Each Row In UsedRange.Rows    For Each cell In Row.Cells        If IsEmpty(cell) Then             Exit For        End If         'Do what you want here...     Next cell Next Row 


回答2:

UsedRange will return a jointed range. In your case, a small test:

Sub test() Debug.Print UsedRange.Address End Sub 

prints $A$1:$F$4

So, you'd better check if there is any value in your cell before you execute your code.

See this SO thread: How to check if a cell is empty? to do so.



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