VBA删除行if

时间:2017-06-12 08:09:21

标签: excel vba excel-vba delete-row

我想要做的就是优化我当前的删除行代码。 在这个阶段,这一步需要很长时间。

        Dim miesiac2 As Integer '--->current month
        miesiac2 = Range("b1").Value
        Dim LastRow As Long
        LastRow = [A65536].End(xlUp).Row
        For i = LastRow To 1 Step -1
        If Cells(i, 1) = miesiac2 Then Rows(i & ":" & i).EntireRow.Delete
        Next i

所以......如果列A等于当前月份,则为EntireRow.Delete 任何的想法?

2 个答案:

答案 0 :(得分:1)

到目前为止,我已经建立了这样的东西:

Option Explicit

Public Sub TestMe()

    Application.ScreenUpdating = False

    Dim miesiac2        As Long
    Dim LastRow         As Long
    Dim i               As Long
    Dim rRange          As Range

    miesiac2 = Range("b1").Value
    LastRow = [A65536].End(xlUp).Row 'xl2003

    For i = LastRow To 1 Step -1
        If Cells(i, 1) = miesiac2 Then
            If rRange Is Nothing Then
                Set rRange = Rows(i)
            Else
                Set rRange = Union(rRange, Rows(i))
            End If
        End If
    Next i

    If Not rRange Is Nothing Then rRange.Select

    Application.ScreenUpdating = True
End Sub

它使用Union并选择行而不是删除它们。它是出于可见性原因,但您可以修复它。 此外,65K行仅在Excel 2003中,在以后的版本中,行为1Mln +。最后但并非最不重要的 - 不要在Excel中使用integer,它的速度很慢且很危险。

答案 1 :(得分:0)

这就是我能赶时间做饭的事情

Sub delete_on_condition()
    Dim wb_export As Workbook
    Dim wb_export_sheet As Worksheet
    Dim arr_raw_dump As Variant
    Dim arr_final
    Dim findcell As Range

    Set wb_export = ThisWorkbook ' CHANGE IT IF REQURIED
    Set wb_export_sheet = wb_export.Sheets(1)    'CHANGE IT IF REQUIRED

    Dim ctr As Long
    ctr = 0
    With wb_export_sheet.Range("A1").CurrentRegion ' OR With wb_export_sheet.USEDRANGE

    Do
         Set findcell = .Find("SOME TEXT")
            If ctr = 0 And findcell Is Nothing Then
                MsgBox "No data found"
                Exit Sub
            End If

         wb_export_sheet.Rows(findcell.Row).Delete
         Set findcell = .Find("SOMETEXT")
         ctr = ctr + 1
    Loop While Not findcell Is Nothing
    End With
End Sub