删除包含特定值的行 VBA

Delete Rows that contain a specific value VBA

我想创建一个简单的程序来搜索 'In Shout?' 列,搜索该列中的所有“#N/A”并删除这些行。

当我在下面 运行 时,它不会删除行,我不明白为什么。谁能看出为什么?

Sub DeleteBadRows()

    Dim InShout As Long
    Dim NA As String
    
    NA = "#N/A"

    'Declaring year value of 1 month & 2 month
    'This is important to compare datasets from 2 months ago & last month
    Year_2M = Format(Date - 57, "YYYY")

    'Declaring month value of 1 month & 2 month
    'This is important to compare datasets from 2 months ago & last month
    Month_2M = Format(Date - 57, "MM")

    'This translates the current month from number to character format
    MonthChar_2 = MonthName(Month_2M, False)

    sheet = "MASTERFILE_" & Year_2M & Month_2M
    
    'setting string values so that we can identify open workbooks
    myFile = "Dataset"
    otherFile = "Monthly Reporting Tool"
    shoutFile = "Copy of Daily Shout"
    
        'if tool wb is open, declare it as MonthlyRepTool
    For Each wb In Application.Workbooks
        If wb.Name Like otherFile & "*" Then
           Set MonthlyRepTool = Workbooks(wb.Name)
        End If
    Next wb
    
        With MonthlyRepTool.Worksheets(sheet).Rows(1)
            Set e = .Find("In Shout?", LookIn:=xlValues)
            InShout = e.Column
        End With

    lastRow = MonthlyRepTool.Worksheets(sheet).Cells(Rows.count, "A").End(xlUp).Row

    For i = 2 To lastRow Step -1

        If MonthlyRepTool.Worksheets(sheet).Cells(i, InShout).value = NA Then
            MonthlyRepTool.Worksheets(sheet).Rows(i).EntireRow.Delete
        End If
        
    Next i

End Sub

当您应该测试错误值时,您正在使用文字文本“N/A”的测试。如果您修改下面的代码,我认为这可能会解决您的问题。此外,(正如蒂姆威廉姆斯指出的那样),你走错了方向。他的回答显示了一个解决方法。下面的变化从下到下。在过程结束时删除行也更有效。我包含了代码来实现这一点。

Dim KillRange As Range

'change 
For i = 2 To lastRow

If IsError(MonthlyRepTool.Worksheets(Sheet).Cells(i, InShout).Value) Then
    If KillRange Is Nothing Then
        Set KillRange = MonthlyRepTool.Worksheets(Sheet).Rows(i).EntireRow
    Else
        Set KillRange = Union(KillRange, MonthlyRepTool.Worksheets(Sheet).Rows(i).EntireRow)
    
    End If
    
End If

Next i

'Delete after the loop
If Not KillRange Is Nothing Then
    KillRange.Delete
End If
For i = 2 To lastRow Step -1

应该是

For lastRow  to 2 Step -1

测试了你的代码。两件事:

  1. 而不是If MonthlyRepTool.Worksheets(sheet).Cells(i, InShout).value = NA Then
    使用 If Application.IsNa(MonthlyRepTool.Worksheets(Sheet).Cells(i, InShout).Value) Then

  2. 而不是For i = 2 To lastRow Step -1
    使用 For i = lastRow To 2 Step -1