我正在嘗試撰寫一個宏來洗掉行,條件是 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
我究竟做錯了什么?
uj5u.com熱心網友回復:
請測驗下一個版本。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
一次洗掉一行,需要很多時間,您只需要處理包含資料的范圍......
請在測驗后發送一些反饋。
uj5u.com熱心網友回復:
=
檢查相同的字串,因此除非您有一個包含"*--*"
or的單元格,否則"*-4*"
If 子句永遠不會為真。您將不得不使用like
-operator:
If cell.Value like "*--*" Or cell.Value like "*-4*" Then
兩點說明:
您的代碼將遍歷整個 Excel 作業表(其中包含 1'048'576 行),因此將運行很長時間。而且,更糟糕的是,如果您添加檢查空單元格以洗掉一行,它將洗掉一百萬行,并且看起來 Excel/VBA 好像被凍結了。因此,您需要在運行代碼之前找出最后一行。在 Excel VBA 中查找最后使用的單元格中的更多資訊
而且您需要注意該代碼將在活動作業表上運行 - 當前具有焦點的作業表。您應該始終指定要撰寫代碼的作業表(和作業簿)。Select
如果處于活動狀態,請不要沿著作業表的路徑前進。有關更多詳細資訊,請參閱如何避免在 Excel VBA 中使用 Select
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
uj5u.com熱心網友回復:
您可以使用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/
我希望這會有所幫助:D
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/526514.html
標籤:vba