excel - 当行的一部分是表格时,Excel VBA无法删除整行
问题描述
我正在尝试遍历我的数据和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 解决方案,其中行的一部分是表?
解决方案
这是从名为 的表中删除第 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
推荐阅读
- python - 使用 round() 对连续值进行分箱会产生伪影
- javascript - javascript中的-->运算符是什么?
- sql-server - 离线时通过 MS Access 前端访问 SQL Server 数据库有哪些选择
- proxy - 如何在 AWS Lambda 函数中附加代理以避免“403 禁止错误”?
- google-bigquery - BQ 切换到 TIMESTAMP 分区表
- javascript - 循环对象 n HTML
- java - 填充从两个不同类获取数据的 TableView
- c# - 检查多个 XML 文件
- javascript - 用很多键替换对象数组中的一些值
- angular - 使用 Angular Router 路由到不同端口上的应用程序