代码之家  ›  专栏  ›  技术社区  ›  DirtyDeffy

当部分行是表时,Excel VBA无法删除整行

  •  1
  • DirtyDeffy  · 技术社区  · 7 年前

    我试着循环浏览我的数据 Union 以后需要删除的某些行号。下面的代码存储了正确的行,但我不能删除它们。我相信这是因为我的数据被安排在一个表中,因为如果数据不在表中,我可以删除所需的行。我收到错误信息 'run time error 1004 - delete method of range class failed' 在线 Urng.delete .

    Sub DeleteRows()
    Dim ws4 As Worksheet: Set ws4 = Worksheets("Sheet1") 
    Dim LastRow As Long 
    Dim CurrentRow As Long
    Dim GroupValue
    Dim GroupTotal As Long
    Dim x As Long
    Dim Urng As Range
    
    Application.ScreenUpdating = False
    ws4.Activate
    
    GroupValue = ws4.Range("B6").Value
    CurrentRow = 6     LastRow = ws4.Cells(Rows.Count, "B").End(xlUp).Row
    Set Urng = Rows(LastRow + 1)
    
        For x = 1 To LastRow 
            GroupTotal = Application.WorksheetFunction.CountIf(Range("B6:B" & LastRow), GroupValue)
            If GroupTotal = 1 Then
                Set Urng = Union(Urng, Rows(CurrentRow))
            End If
    
            CurrentRow = CurrentRow + GroupTotal
            GroupValue = Range("B" & CurrentRow).Value     
            If GroupValue = "" Then ' 
                Exit For
            End If
    
        Next x
    
    Urng.Delete
    Application.ScreenUpdating = True
    End Sub
    

    我试过用 .EntireRow.Delete 没有运气。

    表外没有数据,因此只删除表行可能是一个解决方案,但是,我不知道如何构建 Unions 如果我不能使用 Union(Urng, Rows(CurrentRow)) .

    是否有VBA解决方案可以删除多个整行(其中一部分是表)?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Vityata    7 年前

    这是如何从名为 TableName :

    Sub TestMe()
        Range("TableName[#All]").ListObject.ListRows(5).Delete
    End Sub
    

    关于你的具体问题,情况是 Urng 您有行,它们都在表内和表外。因此,不能用 .Delete . 写在前面 Urng.Delete 看看你自己:

    Urng.Select
    Stop
    Unrg.Delete
    

    在示例中,您可以看到 6 在表格和行中 18 在桌子外面:

    enter image description here


    关于删除表中不相邻的两行,我想唯一的方法是循环。它确实有点慢,但它可以工作:

    Sub TestMe()
    
        Dim cnt As Long
        Dim arrRows As Variant: arrRows = Array(10, 12)
        Dim table As ListObject: Set table = ActiveSheet.ListObjects("SomeTable")
    
        For cnt = UBound(arrRows) To LBound(arrRows) Step -1
            table.ListRows(arrRows(cnt)).Delete
        Next cnt
    
        'This works only when the rows are after each other, e.g. 2,3,4
        table.Range.Rows("2:4").Select
        Stop
        table.Range.Rows("2:4").Delete
    
    End Sub