首页 > 解决方案 > 如何删除带有选定文本的行?

问题描述

我有 sheet1,列“B”上的每个其他单元格都有以下字母“LLC”。我的 vba 脚本应该清除所有“LLC”并水平删除整个 ROW。

我已经使用的代码:

Sub deleteRowswithSelectedText()
For Each CELL In Selection
   If CELL.Value(i, 2) = "LLC" Then
      Rows(CELL.Row).ClearContents
   End If
Next
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.EntireRow.Delete
End Sub

标签: excelvba

解决方案


试试这个,如果你想遍历每个单元格并测试它,你可以,但你需要从底部循环到顶部。另一种方法是使用过滤器并同时删除所有可见行。

Dim lr As Long
Dim i As Long

lr = Cells(Rows.Count, 1).End(xlUp).Row

    For i = lr - 1 To 2 Step -1
        If Cells(i, "B") = "LLC" Then
            Cells(i, "B").EntireRow.Delete
        End If
    Next i

另一种方法是使用过滤器并删除 B 列中包含“LLC”的每一行

With ActiveSheet
    .AutoFilterMode = False
        With Range("A1").CurrentRegion
            .AutoFilter Field:=2, Criteria1:="LLC"
            On Error Resume Next
            .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End With
    .AutoFilterMode = False
End With

这些只是示例,有很多方法可以完成此任务。

下面的代码可能更接近您想要做的事情。

With Sheets("Sheet1") 'Change to your worksheet name
    For Each CELL In .Range("B2:B" & Cells(Rows.Count, "B").End(xlUp).Row)
        If CELL.Value = "LLC" Then
            CELL.EntireRow.Delete
        End If
    Next CELL
End With

推荐阅读