1

我正在尝试遍历我的数据和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 解决方案,其中行的一部分是表?

4

1 回答 1

1

这是从名为 的表中删除第 5 行的方法TableName

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

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

Urng.Select
Stop
Unrg.Delete

在示例中,您可能会看到行在6表中,行在18表外:

在此处输入图像描述


关于删除表中彼此不接近的两行,我想唯一的方法是循环。它确实有点慢,但它有效:

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
于 2018-06-04T09:22:44.537 回答