【问题标题】:how to delete row with condition (VBA)如何删除有条件的行(VBA)
【发布时间】:2022-08-18 17:58:20
【问题描述】:

这是我的excel输出:

红色的在 A 和 B 中具有相同的值。 蓝色的是重复。

在这两种情况下,我都希望删除行。

所以输出看起来像这样:

我试过这样:

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

但它只删除以下行:

    标签: excel vba


    【解决方案1】:

    如何从集合中删除条目?这是一个常见的问题:-)

    让我举个例子说明它是如何出错的,通过使用以下伪代码从集合(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, 6, 7, 8)
    4       (1, 6, 7, 8)       remove fourth => (1, 6, 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 2011-11-30
      • 2017-06-08
      相关资源
      最近更新 更多