Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

excel - Iterating through populated rows

So I am trying to iterate through a worksheet in an Excel spreadsheet using VBA. I want to iterate through each row, and then through each column, and despite googling, I can't actually find an intuitive way to do this.

I'm assuming that the first cell of a row must be populated, if its not, then that must be the end. I can enforce this

My current approach is to iterate through the rows, then try and get the value of the first cell, but I can't figure it out. I've come across some questions here and elsewhere that use ranges and such, but nothing that helps me write code.

The current approach is:

Set sh = ActiveSheet
RowCount = 0
For Each rw In sh.Rows
    'If Row.Cells(1, 1).Value = "" Then Exit For
    RowCount = RowCount + 1
Next rw
MsgBox (RowCount)

Now when I run this, I get some huge number, which is wrong as the table only has about 25 rows. I commented the first line out as it wasn't working.

What can I change in the first line in the For Loop to correctly break when it finds a row where the first cell is empty?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For the benefit of anyone searching for similar, see worksheet .UsedRange,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...