删除VBA中的行,具体取决于值

时间:2015-08-11 12:12:56

标签: excel vba excel-vba

我目前正在开发一个vba项目,我坚持(基本上是)第一部分。

我需要删除数据集中包含第I列

中文本'False'的所有行

不使用过滤器和删除行执行此操作的原因是我正在为其他人自动生成报告,并希望只需单击一个按钮即可生成整个报告。

下面的代码是我所拥有的,它编译没有任何错误......但似乎并没有真正做任何事情。

快速注意,还有其他工作表包含引用此工作表的公式,它是较大程序的一部分,因此我无法删除工作表,只粘贴“有效”数据

Option Explicit

Sub Remfal()
  Application.ScreenUpdating = False

    Dim Firstrow As Long
    Dim Lastrow As Long
    Dim Lrow As Long
    Dim ws1 As Worksheet

   Set ws1 = Sheets("Dataset")

   With ws1

    Firstrow = Cells(Rows.Count, "I").End(xlDown).Row
    Lastrow = Cells(Rows.Count, "I").End(xlUp).Row

    For Lrow = Lastrow To Firstrow Step -1

        With .Cells(Lrow, "I")

            If .Value = "False" Then .EntireRow.Delete

        End With
    Next Lrow
   End With
  Application.ScreenUpdating = True

End Sub

3 个答案:

答案 0 :(得分:0)

你的FirstRow错了,这就是原因。你从最后一行开始尝试下降。它不起作用!尝试给第一行代码名称并使用它代替!防爆。如果你称之为FirstRow:

FirstRow = Sheet1.Range("FirstRow").Row

要确保使用正确的值,请写

debug.print firstrow & " " & lastrow

设置值后。

我不确定你为什么要找到第一行,因为通常用户从顶部开始。除非有一些“假”错误。您希望在第I列中忽略的值,只需将范围从1设置为最后一行。

另外,除了设置application.screenupdating = false之外,我建议您将Calculation设置为xlManual并在结尾处将其放回xlAutomatic。如果您的表格中有公式,这将有很大帮助。

答案 1 :(得分:0)

我找到了一些要清理的东西。

Sub Remfal()

    Application.ScreenUpdating = False

    Dim Firstrow As Long
    Dim Lastrow As Long
    Dim Lrow As Long
    Dim ws1 As Worksheet

    Set ws1 = Sheets(1)

    With ws1

        Firstrow = .Cells(1, "I").End(xlDown).Row 'Notice the "." in front of Cells; also i start at I1 and go down (may not be what you want), rather than start at bottom and go down
        Lastrow = .Cells(Rows.Count, "I").End(xlUp).Row
    End With

    For Lrow = Lastrow To Firstrow Step -1

        With ws1.Cells(Lrow, "I") 'You cant "With" within a "With" statement reliably in VBA; instead I closed the old statement and opened a new one

            If .Formula = False Then 'Using .Formula instead of .Value avoids picking up blank values as FALSE; also changed "False" to False, as its a boolean value not text

                .EntireRow.Delete
            End If

        End With
    Next Lrow

    Application.ScreenUpdating = True

End Sub

答案 2 :(得分:0)

您不需要使用“With”语句来编辑一个已定义的工作表。

Sub Remfal()
Application.ScreenUpdating = False

Dim Firstrow As Long
Dim Lastrow As Long
Dim Lrow As Long
Dim ws1 As Worksheet

Set ws1 = Sheets("Dataset")
Firstrow = ws1.Range("I1").End(xlUp).Row
Lastrow = Lastrow = ws1.Cells(ws1.Rows.Count, "I").End(xlUp).Row 'edit before Grade report
For Lrow = Lastrow To Firstrow Step -1
    If ws1.Cells(Lrow, "I").Value = "False" Then ws1.Cells(Lrow, "I").EntireRow.Delete
Next Lrow
Application.ScreenUpdating = True
End Sub