循环通过第一个非空细胞到最后一个非空细胞

时间:2016-09-28 05:06:02

标签: excel-vba vba excel

我试图循环第一次出现一个单元格到一些未知的最后一个非空单元格。例如。

我知道如何找到最后第一个非空单元格,但我该怎么办 他们在一个循环中?

 With Worksheets("AssignedTickets").Columns("F")
    Set test = .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues)
End With

enter image description here

1 个答案:

答案 0 :(得分:2)

以下是一些技巧:

enter image description here

Sub LoopThroughCells()
    Dim c As Range, Target As Range, rFirst As Range, rLast As Range
    Dim x As Long, y As Long

    With Worksheets("Sheet1").Cells
        Set rLast = .Find(What:="*", _
                          After:=.Cells(1), _
                          Lookat:=xlPart, _
                          LookIn:=xlFormulas, _
                          SearchOrder:=xlByRows, _
                          SearchDirection:=xlPrevious, _
                          MatchCase:=False)

        Set rFirst = .Find(What:="*", _
                           After:=rLast, _
                           Lookat:=xlPart, _
                           LookIn:=xlFormulas, _
                           SearchOrder:=xlByRows, _
                           SearchDirection:=xlNext, _
                           MatchCase:=False)


        With .Range(rFirst, rLast)
            Debug.Print "For Each c In .Cells"
            For Each c In .Cells
                If x <> c.Row Then Debug.Print
                x = c.Row
                Debug.Print c.Value,
            Next
Stop
            Debug.Print
            Debug.Print "For x = 1 To .Rows.Count"
            For x = 1 To .Rows.Count
                Debug.Print

                For y = 1 To .Columns.Count
                    Debug.Print .Cells(x, y),
                Next
            Next

        End With
    End With


End Sub

注意:For Each Loop逐行迭代一个范围(例如,行(1)中的所有单元格,然后是行(2)中的所有单元格。)。

UPDATE:

从第一个使用过的单元格和最后一个使用过的单元格开始选择范围;不使用find。

 With Worksheets("Sheet1")
    With .Range(.Range("C1").End(xlDown), .Range("C" & Rows.Count).End(xlUp))
        For Each c In .Cells
            If x <> c.Row Then Debug.Print
            x = c.Row
            Debug.Print c.Value,
        Next
    End With
End With