循环遍历excel中未知的行范围

时间:2015-04-23 03:36:31

标签: excel vba loops excel-vba

说我有5列,天知道有多少行。除了最后一列中的一些单元格外,此范围内的所有单元格都已填充。 我需要遍历所有行(从A1开始)直到我到达最后一行,并且对于在最后一列中填充了一个单元格的每一行,显示一个消息框,说明"你好"

我真的不确定如何启动循环。 我试过谷歌搜索,但我不明白。我知道我如何检查空单元格,以及如何浸入消息框,但不知道如何找到范围的结尾。

3 个答案:

答案 0 :(得分:0)

只要没有完全空白的列或行,.currentregion属性就会提供对完整矩形单元格块的引用。

dim rw as long
with activesheet.cells(1, 1).currentregion
    for rw = 1 to .rows.count
        if not isempty(.cells(rw, 5)) then
            msgbox .cells(rw, 5).address(0, 0) & " has a value (" & .cells(rw, 5).value & ")"
        end if
    next rw
end with

答案 1 :(得分:0)

我身边的其他变种

Dim cl As Range
With ActiveSheet
    For Each cl In .Range(.[A1].CurrentRegion.Columns(5).Address)
        If cl.Value <> "" Then
            MsgBox cl.Address(0, 0) & " has a value (" & cl.Value & ")"
        End If
    Next cl
End With

答案 2 :(得分:0)

很多版本

Sub Button1_Click()
    Dim Rws As Long, Rng As Range, c As Range, x
    Rws = Cells(Rows.Count, "A").End(xlUp).Row
    Set Rng = Range(Cells(1, 1), Cells(Rws, 1))

    For Each c In Rng.Cells
        x = WorksheetFunction.CountA(Range(Cells(c.Row, 1), Cells(c.Row, 5)))
        If x = 5 Then MsgBox "Hello! Row #- " & c.Row & " has 5!"
    Next c

End Sub