Bru*_*yne 4 excel vba delete-row
通常需要您浏览一系列单元格,并根据某些条件删除整行.
在实践中,最好从范围的最后开始,并开始工作.
Dim i as Long
For i = lastRow to 1 Step -1
If Cells(i, 2).Value = "del" then Rows(i).EntireRow.Delete
End if
Run Code Online (Sandbox Code Playgroud)
但是,大部分时间我都在使用一个Range
对象.
有没有办法向后工作,使用范围对象,不需要使用For i
类型循环?
Dim rng as Range, cel as Range
Set rng = Range("A1:A100")
For each cel in rng step -1
if cel.value = "del" then cel.EntireRow.Delete
next cel
Run Code Online (Sandbox Code Playgroud)
这种错误Expected: End of Statement
的Step -1
部分,这是我预期的(没有双关语意).
我的想法是,Cells()
在尝试向后处理Range
变量时,我基本上不必重新安排数据.我发现使用范围变量一堆有点麻烦,但是当想要从该范围中删除行时,Cells([long],[long])
如果有意义则必须切换到使用.
编辑:刚刚提出这个,但它仍然感觉kludgy:
Dim k As Long, cel as Range
Set cel = rng.cells(rng.cells.count)
For k = cel.Row To rng.Cells(1).Row Step -1
If rng.Cells(k).Value = "del" Then rng.Cells(k).EntireRow.Delete
Next k
Run Code Online (Sandbox Code Playgroud)
是的,你可以在没有For i =
声明的情况下完成.只需创建一个特殊范围,您将在完成循环后删除该范围.
Dim cel As Range, rng As Range
Dim delRng As Range
For Each cel In rng
If cel.Value = "del" Then
If delRng Is Nothing Then
Set delRng = cel
Else
Set delRng = Union(delRng, cel)
End If
End If
Next cel
If Not delRng Is Nothing Then delRng.EntireRow.Delete
Run Code Online (Sandbox Code Playgroud)
你甚至不必倒退.
归档时间: |
|
查看次数: |
217 次 |
最近记录: |