【问题标题】:VBA Quickly find and delete rows if column value="" [duplicate]如果列值=“”,VBA快速查找和删除行[重复]
【发布时间】:2019-01-04 19:43:55
【问题描述】:

我创建了一个宏来生成每日报告。但是,它需要很长时间才能运行。在 AN 列中查找值并删除整行的宏部分需要小步舞曲才能运行。

以下示例删除 AN 列中所有不包含值“CAT”的行。

有没有更有效的方法来编写代码,这样它就不会花很长时间运行?可能还为其他值添加一个数组? (猫、狗、牛) 谢谢!

代码效率低下(工作,但由于数百行而运行时间很长):

'False screen updating
Application.ScreenUpdating = False
'deleting all other types other than CAT from "samples" tab (excluding the header row, row 1)
Sheets("sample").Select
LastRowNum = Cells.SpecialCells(xlCellTypeLastCell).Row
ReadRow = 2
For n = 2 To LastRowNum
    If Range("AN" & ReadRow).Value <> "CAT" Then
    Range("AN" & ReadRow).EntireRow.Delete
Else
  ReadRow = ReadRow + 1
End If

【问题讨论】:

  • 关闭自动计算和屏幕更新
  • 整个For n = 2 To LastRowNum 循环非常错误。
  • @user10862412 我不确定为什么 n = 2 在代码中,因为 n 不是声明的变量。我在网上找到了一些代码,它完成了工作,所以我没有更改任何代码。
  • @ArcherBird 我添加了“Application.ScreenUpdating = False”,但是检查 4000 行仍然需要很长时间。有没有办法添加任何数组以提高循环的效率?

标签: excel vba performance delete-row


【解决方案1】:

使用联合并删除一次:

With Worksheets("sample")
    Dim LastRowNum As Long
    LastRowNum = .Cells(.Rows.Count, "AN").End(xlUp).Row


    Dim rng As Range

    Dim n As Long
    For n = 2 To LastRowNum
        If .Range("AN" & n).Value <> "CAT" Then
            If rng Is Nothing Then
                Set rng = .Rows(n)
            Else
                Set rng = Union(rng, .Rows(n))
            End If
        End If
    Next n

    rng.EntireRow.Delete
End With

【讨论】:

    【解决方案2】:

    这是一种删除空白行的方法,应该相当快。

    Public Sub RemoveBlankRows(ws As Worksheet)
    On Error GoTo errorHandler:
    
        Application.ScreenUpdating = False
        Application.Calculation = xlCalculationManual
    
        Dim LastRow As Long
        LastRow = ws.Cells.Find(What:="*", After:=ws.Range("A1"), LookAt:=xlPart, LookIn:=xlFormulas, _
                                SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
    
        For i = LastRow To 1 Step -1
            If WorksheetFunction.CountA(ws.Cells(i, 1).EntireRow) = 0 Then ws.Rows(i).Delete Shift:=xlShiftUp
        Next
    
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
    
        Exit Sub
    
    errorHandler:
        Application.ScreenUpdating = True
        Application.Calculation = xlCalculationAutomatic
    End Sub
    
    Sub ExampleUsage()
         RemoveBlankRows ThisWorkbook.Sheets("Sheet1")
    End Sub  
    

    【讨论】:

    • 如果工作簿中有很多公式,您也应该在其中添加Application.Calculation = xlCalculationManual
    • 肯定是一个很好的优化,请参阅编辑
    猜你喜欢
    • 2017-12-25
    • 2015-03-06
    • 2014-09-24
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2019-09-26
    • 2018-11-21
    • 2012-12-29
    相关资源
    最近更新 更多