我试图编写一个宏,删除行,条件是A列中的字符串包含"--“或"-4”或"“(空)。我会用一个普通的过滤器,但这给了我最多2个条件。
Sub Delete_Rows()
Dim cell As Range
For Each cell In Range("A:A")
If cell.Value = "*--*" Or cell.Value = "*-4*" Then
cell.EntireRow.Delete
End If
Next cell
End Sub我做错了什么?
发布于 2022-11-02 08:30:05
请测试下一个版本。它使用一个用于迭代的数组和一个Union范围同时删除代码末尾的行:
Sub Delete_Rows3Cond()
Dim sh As Worksheet, lastR As Long, rngDel As Range, arr, i As Long
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
arr = sh.Range("A1:A" & lastR).Value2 'place the range in an array for faster iteration/processing only in memory
For i = 1 To UBound(arr)
If arr(i, 1) = "" Or arr(i, 1) Like "*--*" Or arr(i, 1) Like "*-4*" Then
addToRange rngDel, sh.Range("A" & i) 'create the union range
End If
Next
If Not rngDel Is Nothing Then rngDel.EntireRow.Delete xlUp
End Sub
Private Sub addToRange(rngU As Range, Rng As Range) 'I creates the Union range
If rngU Is Nothing Then
Set rngU = Rng
Else
Set rngU = Union(rngU, Rng)
End If
End Sub每次删除一行需要花费大量时间,您只需处理包含数据的范围.
请在测试后发送一些反馈信息。
发布于 2022-11-02 08:32:29
=检查相同的字符串,因此除非有包含"*--*"或"*-4*"的单元格,否则If-子句将永远不会为真。您必须使用like-operator:
If cell.Value like "*--*" Or cell.Value like "*-4*" Then两点意见:
您的代码将遍历整个Excel表(其中包含1'048'576行),以便运行很长时间。更糟糕的是,如果添加检查空单元格以删除一行,它将删除100万行,并且看起来就像冻结了Excel/VBA。因此,您需要在运行代码之前确定最后一行。在Find last used cell in Excel VBA上有更多关于这个的信息。
您需要知道,该代码将运行在活动工作表上--当前具有焦点的工作表。您应该始终指定要使用代码的工作表(和工作簿)。如果是活动的,不要沿着Select表的路径前进。有关详细信息,请参阅How to avoid using Select in Excel VBA
Sub Delete_Rows()
Dim cell As Range, lastRow As Long
' Replace the following line with the workbook you want to work with
With ThisWorkbook.Sheets(1)
lastRow = .Cells(.Rows.Count, "A").End(xlUp).row
For Each cell In .Range("A1:A" & lastRow)
If cell.Value Like "*--*" Or cell.Value Like "*-4*" Then
cell.EntireRow.Delete
End If
Next cell
End With
End Sub发布于 2022-11-02 08:22:56
您可以使用Like运算符而不是"=“来执行比较。请考虑以下代码:
Sub Delete_Rows()
Dim cell As Range
For Each cell In Range("A:A")
If cell.Value Like "*--*" Or cell.Value Like "*-4*" Then
cell.EntireRow.Delete
End If
Next cell
End Sub您还可以在这里阅读有关like运算符的更多信息,例如:https://www.wallstreetmojo.com/vba-like/
我希望这能有所帮助。
https://stackoverflow.com/questions/74286092
复制相似问题