gpt4 book ai didi

vba - 根据列值删除行

转载 作者:行者123 更新时间:2023-12-04 22:32:01 24 4
gpt4 key购买 nike

我想检查一个单元格(“C”)是否不包含日期或为空以删除特定行。我的代码没有删除所有具体的行,而且对于行数(138)来说似乎太慢了。

lastrow = pertes.Cells(pertes.Rows.count, "A").End(xlUp).Row
For i = 2 To lastrow
If Not IsDate(pertes.Cells(i, 3).Value) Or IsEmpty(pertes.Cells(i, 3).Value) Then
pertes.Rows(i).Delete
End If
Next i

最佳答案

如果您逐一删除或添加行,则循环必须向后:

For i = lastrow To 2 Step -1 

否则删除会更改行数,因此循环计数错误。

为了使其更快,您可以使用 Union() 收集范围内必须删除的所有行。 ,最后一次性全部删除。这更快,因为每个删除操作都需要时间,并将操作数量减少到 1。
Option Explicit

Public Sub DeleteRows()
Dim LastRow As Long
LastRow = pertes.Cells(pertes.Rows.Count, "A").End(xlUp).Row

Dim RowsToDelete As Range '… to collect all rows

Dim i As Long
For i = 2 To LastRow 'forward or backward loop possible
If Not IsDate(pertes.Cells(i, 3).Value) Or IsEmpty(pertes.Cells(i, 3).Value) Then
If RowsToDelete Is Nothing Then 'collect first row
Set RowsToDelete = pertes.Rows(i)
Else 'add more rows to that range
Set RowsToDelete = Union(RowsToDelete, pertes.Rows(i))
End If
End If
Next i

RowsToDelete.Delete 'delete all rows at once
End Sub

请注意,这里我们不需要向后循环,因为我们在循环后立即删除所有行。

关于vba - 根据列值删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51950213/

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