首页 > 解决方案 > 尝试在我的范围内删除具有错误值的行

问题描述

我很确定我快到了。目前这会删除所有行。我只是希望它删除标识为其中包含该单词的行FALSE

Dim R As Range
Dim myRange As Range

LastRow = Range("A" & Rows.Count).End(xlUp).Row

Set myRange = Range("U2:U" & LastRow)

For Each R In myRange
    If R.Value = "FALSE" Then
        Rows.Delete
    End If
Next

我也尝试过使用下面的代码,但没有帮助。

Dim R As Range
Dim myRange As Range

LastRow = Range("A" & Rows.Count).End(xlUp).Row

Set myRange = Range("U2:U" & LastRow)

For Each R In myRange
    If R = "False" Then
        R.EntireRow.Delete
    End If
Next```

这是如何存储值的屏幕截图。这是一个从 Vlookup 中剥离并转换为值的字段。 在此处输入图像描述

标签: excelvba

解决方案


使用False可能会很棘手,所以我为您创建了一个示例,如下所示。

在此处输入图像描述

正如我在评论中建议的那样,不要使用循环。如根据部分文本删除行Autofilter中所述使用

尝试这个

代码:

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim SearchValue As Boolean
    Dim lRow As Long

    SearchValue = False
    
    '~~> Change this to the relevant sheet
    Set ws = Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        '~~> Remove any filters
        .AutoFilterMode = False

        '~~> Filter, offset(to exclude headers) and delete visible rows
        With .Range("U1:U" & lRow)
          .AutoFilter Field:=1, Criteria1:=SearchValue
          .Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End With

        '~~> Remove any filters
        .AutoFilterMode = False
    End With
End Sub

最后结果:

在此处输入图像描述

笔记:

如果这对您有用,我将把这个问题作为一个副本关闭,但保留这个答案,因为它显示了如何处理布尔值和布尔值(存储为字符串)值。


推荐阅读