我试图循环第一次出现一个单元格到一些未知的最后一个非空单元格。例如。
我知道如何找到最后和第一个非空单元格,但我该怎么办 他们在一个循环中?
With Worksheets("AssignedTickets").Columns("F")
Set test = .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues)
End With
答案 0 :(得分:2)
以下是一些技巧:
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)中的所有单元格。)。
从第一个使用过的单元格和最后一个使用过的单元格开始选择范围;不使用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