我希望VBA循环工作表中的行,并根据满足条件的行设置范围。
目前,我的代码仅选择条件为true的第一行,并且我希望满足条件的所有行都包含在设置范围内...
Sub setrng()
Set WkSht = Sheets("Main")
For i = 1 To 335
If WkSht.Cells(i, 8).Value = "Y" And WkSht.Cells(i, 9).Value = "ZC" And WkSht.Cells(i, 10).Value = "N" Then
Dim rng As Range
With Application.Intersect(WkSht.Rows(i), WkSht.UsedRange)
Set rng(i) = WkSht.Range(WkSht.Cells(i, 3), .Cells(.Cells.Count))
End With
If rng Is Nothing Then
Exit Sub
End If
End If
Next
答案 0 :(得分:0)
根据范围建立范围最好由Union完成。一个小问题是,您不能一无所获。在这种情况下(这是第一次迭代),您将必须将收集的范围设置为找到的第一个范围。在那之后,使用union
Sub setrng()
Dim CollectedRange As Range
Dim AddedRange As Range
Set WkSht = Sheets("Main")
For i = 1 To 335
If WkSht.Cells(i, 8).Value = "Y" And WkSht.Cells(i, 9).Value = "ZC" And WkSht.Cells(i, 10).Value = "N" Then
With Application.Intersect(WkSht.Rows(i), WkSht.UsedRange)
Set AddedRange = WkSht.Range(WkSht.Cells(i, 3), .Cells(.Cells.Count))
End With
If Not AddedRange Is Nothing Then
If CollectedRange Is Nothing Then
Set CollectedRange = AddedRange
Else
Set CollectedRange = Union(CollectedRange, AddedRange)
End If
End If
End If
Next
Debug.Print CollectedRange.Address
End Sub