Excel VBA当行的一部分是表时,不能删除整行

时间:2018-06-04 09:20:04

标签: excel-vba for-loop runtime-error delete-row set-union

我试图遍历我的数据和 try { Context otherAppContext = getActivity().createPackageContext(""+package_name, Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); Resources mApk1Resources = otherAppContext.getResources(); int mDrawableResID = mApk1Resources.getIdentifier(package_name+":drawable/icon", "drawable", package_name); Drawable myDrawable = mApk1Resources.getDrawable(mDrawableResID); if (myDrawable != null) { data.add(new DataModel("" + app_name, myDrawable, package_name)); } } catch(Exception e) { e.printStackTrace(); } 我需要稍后删除的某些行号。下面的代码存储了正确的行,但我无法删除它们。我相信它是因为我的数据安排在一个表格中,因为如果数据不在表格中,我能够删除所需的行。我在第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中的行号。

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

1 个答案:

答案 0 :(得分:1)

这是从名为TableName

的表中删除第5行的方法
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