所以我试图使用VBA迭代Excel电子表格中的工作表。我想遍历每一行,然后遍历每一列,尽管谷歌搜索,我实际上找不到直观的方法来做到这一点。
我假设必须填充行的第一个单元格,如果不填充,则必须结束。我可以执行这个
我目前的方法是遍历行,然后尝试获取第一个单元格的值,但我无法弄明白。我在这里和其他地方遇到过一些使用范围等的问题,但没有什么可以帮助我编写代码。
目前的做法是:
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)
现在当我运行它时,我得到一些巨大的数字,这是错误的,因为表只有大约25行。我评论了第一行,因为它不起作用。
当找到第一个单元格为空的行时,我可以在For循环的第一行中更改哪些内容正确中断?
答案 0 :(得分:58)
看起来你刚刚对行和列进行了硬编码;否则,几个小调整,我认为你在那里:
Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer
RowCount = 0
Set sh = ActiveSheet
For Each rw In sh.Rows
If sh.Cells(rw.Row, 1).Value = "" Then
Exit For
End If
RowCount = RowCount + 1
Next rw
MsgBox (RowCount)
答案 1 :(得分:52)
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
答案 2 :(得分:17)
我将在答案中做出一些假设。我假设您的数据从A1开始,并且每行的第一列中没有空单元格。
此代码将:
这不是一种快速的方法,但会根据您的意图单独迭代每个方法。
Sub iterateThroughAll()
ScreenUpdating = False
Dim wks As Worksheet
Set wks = ActiveSheet
Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRow As Long
LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row
Set rowRange = wks.Range("A1:A" & LastRow)
'Loop through each row
For Each rrow In rowRange
'Find Last column in current row
LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))
'Loop through all cells in row up to last col
For Each cell In colRange
'Do something to each cell
Debug.Print (cell.Value)
Next cell
Next rrow
ScreenUpdating = True
End Sub