简体   繁体   中英

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

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM