我有一个vba代码,可以根据多个条件删除行。它工作得非常好,我喜欢代码的简短。但是,我注意到它错过了一些包含标准的单元格。通常我只想删除三个左右的列出标准。有任何线索可能会发生这种情况吗?
以下是代码:
Sub DeleteMyRows()
Dim Rng As Range, Cell As Range
Set Rng = Range(Range("B2"), Range("B" & Rows.Count).End(xlUp))
With Application
.ScreenUpdating = False
.EnableEvents = False
For Each Cell In Rng
If Cell = "ADD" Or Cell = "ANFR" Or Cell = "CADV" Or Cell = "DEF" Or Cell = "DEFD" Or Cell = "OIL" Or Cell = "PROP" Or Cell = "STAX" Or Cell = "UREA" Or Cell = "WWFL" Or Cell = "NGAS" Then
Cell.EntireRow.Delete
End If
Next Cell
End With
End Sub
谢谢!
答案 0 :(得分:0)
[答案来自上一个问题:IF-THEN w/ strings in VBA]
如何'相同'是两个字符串?一个是资本化而另一个不是吗?有一个领先/尾随零?是否有不可打印的字符?
尝试这个,在用作比较之前将Cell变为CleanedCell:
CleanedCell = AllCleanedUp(Cell)
If CleanedCell = "ADD" Or CleanedCell = "ANFR" Or CleanedCell = "CADV" Or CleanedCell = "DEF" Or CleanedCell = "DEFD" Or CleanedCell = "OIL" Or CleanedCell = "PROP" Or CleanedCell = "STAX" Or CleanedCell = "UREA" Or CleanedCell = "WWFL" Or CleanedCell = "NGAS" Then
Cell.EntireRow.Delete
End If
...
其中涉及以下功能:
Function AllCleanedUp (DirtyString byVal) As String
AllCleanedUp = Trim(Application.Clean(Ucase(DirtyString)))
End Function
答案 1 :(得分:0)
可能是Cell中的值处于不同的情况,或者具有前导或尾随空格。 (我经常在手动输入数据中发现这个问题)
尝试使用:
If UCase(Trim(Cell.Value)) = "ADD" Or UCase(Trim(Cell.Value)) = "ANFR" Or ....... Then
答案 2 :(得分:0)
这可能是其中一个答案,但我的猜测是问题是当你删除一行时,“cell”成为下一个,然后你点击“next”并完全跳过这一行。 例如,如果你这样做:
Sub test()
Dim cell
For Each cell In Range("A1", "A10")
cell.EntireRow.Delete
Next cell
End Sub
您只会删除第1,3,5,7,9行
你应该反向循环,据我所知,对于范围(...)循环中的每个单元格都不可能,但是可以通过迭代这样的数字来完成:
for i=cells(rows.count,"B").end(xlup).row to 2 step -1
If Cells(i,"B") = "ADD" Or Cells(i,"B") = "ANFR" Or Cells(i,"B") = "CADV" Or Cells(i,"B") = "DEF" Or Cells(i,"B") = "DEFD" Or Cells(i,"B") = "OIL" Or Cells(i,"B") = "PROP" Or Cells(i,"B") = "STAX" Or Cells(i,"B") = "UREA" Or Cells(i,"B") = "WWFL" Or Cells(i,"B") = "NGAS" Then
Cell.EntireRow.Delete
End If
next i
答案 3 :(得分:0)
我喜欢这样做:
If Cell LIKE "*ADD*" Or Cell LIKE "*ANFR*" Or Cell LIKE "*CADV*" Or Cell LIKE "*DEF*" Or Cell LIKE "*DEFD*" Or Cell LIKE "*OIL*" Or Cell LIKE "*PROP*" Or Cell LIKE "*STAX*" Or Cell LIKE "*UREA*" Or Cell LIKE "*WWFL*" Or Cell LIKE "*NGAS*" Then
Cell.EntireRow.Delete
End If
星号(*)表示任何字母,数字,空格......可以在您的给定值之前或之后(在我的示例中)。
希望得到这个帮助。