[英]how to delete row with condition (VBA)
這是我的 excel output:
紅色的在 A 和 B 中具有相同的值。
藍色的是復制品。
在這兩種情況下,我都希望刪除行。
所以 Output 看起來像這樣:
我試過這樣:
Sub delete()
With ThisWorkbook.Worksheets("Table10").Activate
Dim rowsend As Integer
Dim arr() As Variant
Dim element As Variant
Dim rows5 As Variant
rowsend = ActiveSheet.Cells(ActiveSheet.rows.Count, "B").End(xlUp).row
arr = Range("B1:B" & rowsend).Value
Debug.Print rowsend
rows5 = 1
For Each element In arr
If element = Range("A" & rows5).Value Then
Debug.Print "yes"
rows(rows5).delete
Else
Debug.Print "no"
End If
rows5 = rows5 + 1
'Debug.Print element
Next element
End With
End Sub
但它只刪除以下行:
在 worder 中(僅)刪除范圍內的行,您應該向后迭代。
為了有效地執行此操作(一次不是一行),您應該為各個行創建一個Union
范圍並在最后一次刪除它們。 可以以任何方式進行迭代。 請嘗試下一個代碼。 它使用字典和數組僅在 memory 中處理並創建提到的Union
范圍,在末尾刪除:
Sub DeleteRowsDuplic()
Dim sh As Worksheet, lastR As Long, arr, i As Long, rngDel As Range
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).row
arr = sh.Range("A1:B" & lastR).Value2
With CreateObject("scripting.dictionary")
For i = 1 To UBound(arr)
If arr(i, 1) = arr(i, 2) Then
addToRange rngDel, sh.Range("A" & i)
Else
If Not .Exists(arr(i, 1) & arr(i, 2)) Then
.Add arr(i, 1) & arr(i, 2), 1
Else
addToRange rngDel, sh.Range("A" & i)
End If
End If
Next i
End With
If Not rngDel Is Nothing Then rngDel.EntireRow.Delete
End Sub
Sub addToRange(rngU As Range, rng As Range)
If rngU Is Nothing Then
Set rngU = rng
Else
Set rngU = Union(rngU, rng)
End If
End Sub
如果要刪除的范圍變得很大,則創建Union
范圍的速度會減慢,並且代碼不會像合理范圍那樣快。 如果這是你的情況,請 state 它,我將發布另一個代碼也能夠處理這種情況......
如何從集合中刪除條目? 這是一個經常出現的問題:-)
讓我舉一個例子,說明它如何 go 錯誤,通過使用以下偽代碼從集合(1, 2, 4, 6, 7, 8)
中刪除所有偶數值:
int index = 1; // we'll start at 1
while (index < length(collection))
do:
if collection[index] mod 2 = 0
then collection.remove(index);
index = index + 1;
end while
觀察會發生什么:
index collection action and result
1 (1, 2, 4, 6, 7, 8) none
2 (1, 2, 4, 6, 7, 8) remove second => (1, 4, 6, 7, 8)
3 (1, 4, 6, 7, 8) remove third => (1, 4, 7, 8)
4 (1, 4, 7, 8) remove fourth => (1, 4, 7)
什么值 4 沒有被刪除? 好吧,僅僅是因為,由於刪除了第二項,值 4 變成了第二項,循環進入第三項,跳過了值 4。
我們如何解決這個問題? 只需從結尾回到開頭:
int index = length(collection); // we'll start at the end
while (index > 1)
do:
if collection[index] mod 2 = 0
then collection.remove(index);
index = index - 1;
end while
index collection action and result
6 (1, 2, 4, 6, 7, 8) remove sixth => (1, 2, 4, 6, 7)
5 (1, 2, 4, 6, 7) nothing
4 (1, 2, 4, 6, 7) remove fourth => (1, 2, 4, 7)
3 (1, 2, 4, 7) remove third => (1, 2, 7)
2 (1, 2, 7) remove third => (1, 7)
1 (1, 7) nothing
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.