如何从设置范围对象中删除行

How can I delete rows from a set range object

一旦我在 vba 中设置了范围变量,是否有一种方法可以根据值从中删除行 and/or 列单元格?

例如:

Dim Lrange as Range

Set Lrange = Range("A1:E5")

For each row in Lrange
   If cell(Lrange.row, 3).value = "Somestring" Then
       LRange.row.delete
   End if
Next

这可能吗,还是我必须将它存储在工作表中才能操纵范围?

欢迎提出任何建议!

如果您想根据某个值删除工作表中的行,则可以使用如下代码...

Sub DeleteRows()
Dim aRange As Range, aRow As Range, aCell As Range
    Set aRange = Range("A1:E5")
    For Each aRow In aRange.Rows
        For Each aCell In aRow.Cells
            If aCell.Value = "Somestring" Then
                aRow.EntireRow.Delete
                Exit For
            End If
        Next aCell
    Next aRow
End Sub

如果您想根据值更改对象在 VBA 中引用的范围,则可以使用如下代码...

Sub DeleteRowsInObject()
Dim aRange As Range, aRow As Range, aCell As Range
Dim bRange As Range, found As Boolean
    Set aRange = Range("A1:E5")
    For Each aRow In aRange.Rows
        found = False
        For Each aCell In aRow.Cells
            If aCell.Value = "Somestring" Then found = True
        Next aCell
        If Not found Then
            If bRange Is Nothing Then
                Set bRange = aRow
            Else
                Set bRange = Union(bRange, aRow)
            End If
        End If
    Next aRow
    Set aRange = bRange
    Set bRange = Nothing
End Sub

您需要小心处理与其行/列不连续的 Range 对象,因为一些常规属性/方法不一定提供您期望的值。

如果你要删除,你应该通过行向后循环:

Dim Lrange                As Range
Dim n                     As Long
Set Lrange = Range("A1:E5")

For n = Lrange.Rows.Count To 1 Step -1
    If Lrange.Cells(n, 3).Value = "Somestring" Then
        Lrange.Rows(n).Delete
    End If
Next

例如。