VBA中的条件删除 [英] Conditional Delete in VBA
问题描述
我正在拼凑代码,使我的宏正常工作。这种方法在过去一直很好,但似乎不能正确地适应任何代码。
I am trying to piece together code to make my macro work correctly. This approach has served me well in the past but I cannot seem to adapt any code correctly.
我发现以下
Sub way()
Dim Cell As Range
For Each Cell In Range("A1").CurrentRegion
If Len(Cell) < 2 Then Cell.EntireRow.Delete
Next Cell
End Sub
<我可以根据我的喜好调整If Len(Cell)的标准。例如= 10
I can adapt the If Len(Cell) criteria to my liking. For example = 10
我不知道如何调整代码,使其搜索列A中的所有单元格,并删除相应的行。上面的代码只对A1做了。
I do not know how to adapt the code to make it search through all cells in column A and delete the appropriate rows. The code above only does it for A1.
理想情况下,我想删除长度为10个字符的列A中的所有行。或者,使用完全不同的代码集,删除长度为10个字符的列A中不包含单元格的所有其他行。
Ideally I would like to delete all rows with cells in column A that have a length of 10 characters. Or alternatively, with a completely different set of code, delete all other rows that do not contain cells in column A that have a length of 10 characters.
推荐答案
删除行时最好向后循环:
When deleting rows it is best to loop backwards:
Sub way()
Dim ws As Worksheet
Dim i As Long
Dim lastrow As Long
Set ws = ActiveSheet
lastrow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
For i = lastrow To 1 Step -1
If Len(ws.Cells(i, 1)) < 2 Then ws.Rows(i).Delete
Next i
End Sub
这篇关于VBA中的条件删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!