gpt4 book ai didi

excel - 删除行(向后工作),但使用范围变量?

转载 作者:行者123 更新时间:2023-12-02 09:17:51 25 4
gpt4 key购买 nike

通常需要您浏览一系列单元格,并根据某些条件删除整行。

在实践中,最好从范围的末尾开始,然后逐渐增加。

Dim i as Long
For i = lastRow to 1 Step -1
If Cells(i, 2).Value = "del" then Rows(i).EntireRow.Delete
End if

但是,大多数时候我都在使用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

此错误Expected: End of Statement关于Step -1部分,这是我所期望的(没有双关语)。

这个想法是我基本上不必将我的数据重新排列到 Cells()当尝试逆向处理 Range 时多变的。我发现使用一堆范围变量有点笨拙,但是当想要从该范围中删除行时,必须切换到使用 Cells([long],[long])如果这是有道理的。

编辑:刚刚想出这个,但仍然感觉很困惑:

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

最佳答案

是的,您无需使用 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

而且您甚至不必后退。

关于excel - 删除行(向后工作),但使用范围变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53107362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com