简单的循环需要多年

时间:2013-07-26 17:14:23

标签: excel vba excel-vba

我有这个简单的循环,用于查看excel中的数据块: 它首先确定它向下延伸的行数 - 这定义了迭代次数 然后在每一行N上,查看单元格(N,B)是否为空 - 如果是,则删除该行。

这似乎不起作用,也需要很长时间!我需要能够很快完成这项工作的东西。

任何想法都会受到重视

Sub PREBILLvariant2()

        Dim N As Long

 For N = 1 To Worksheets("EMEA input").Cells(Rows.Count, "A").End(xlUp).Row

If InStr(Cells(N, "B").Value, "") > 0 Then Worksheets("EMEA input").Cells(N, "B").EntireRow.Delete


    Next N

    End Sub

3 个答案:

答案 0 :(得分:3)

这是另一种方法。我总是发现过滤是做这些事情的最快方法。

Public Sub filterThenDelete()
    Application.ScreenUpdating = False

    Dim r As Excel.Range
    Set r = Sheets("EMEA input").UsedRange

    r.AutoFilter Field:=2, Criteria1:=""

    Dim deleteRange As Excel.Range
    Set deleteRange = r.Offset(1, 0).Resize(r.Rows.Count - 1, r.Columns.Count).Cells.SpecialCells(xlCellTypeVisible)

    deleteRange.EntireRow.Delete

    Sheets("EMEA input").AutoFilterMode = False
    Application.ScreenUpdating = True
End Sub

只是一个FYI,对于AutoFilter,Field:=2说“将Criteria1中找到的过滤器应用到所选范围内的第2列”。或者只是“过滤列B以获取空白值。”

答案 1 :(得分:2)

这样的事情:

Sub PREBILLvariant3()
    Dim ws As Worksheet
    Dim lRows As Long, N As Long
    Dim rngToDelete As Range

    Application.ScreenUpdating = False
    Set ws = Worksheets("EMEA input")
    lRows = ws.Cells(Rows.Count, "A").End(xlUp).Row
    For N = 1 To lRows
        If ws.Cells(N, "B").Value <> "" Then
            If rngToDelete Is Nothing Then
                Set rngToDelete = ws.Cells(N, "B")
            Else
                Set rngToDelete = Union(rngToDelete, ws.Cells(N, "B"))
            End If
        End If
    Next N
    rngToDelete.EntireRow.Delete
    Application.ScreenUpdating = True
    Set ws = Nothing
End Sub

这将收集B中非空(&lt;&gt;“”)的所有单元格中的Range,并在循环后一次性删除行。

检查非空(&lt;&gt;“”)或Len() > 0比使用InStr()更好的IMO,因为您不需要查找特定文本。

答案 2 :(得分:-2)

这是一种更为标准的方法:

它循环遍历A列中内容的每一行,并删除C列中具有空单元格的每一行

Sub subDeleteRows()
    Dim lngRow As Long: lngRow = 1

    subSpeedUp True

    Do Until IsEmpty(Sheets("EMEA input").Cells(lngRow, 1))
        If IsEmpty(Sheets("EMEA input").Cells(lngRow, 2)) Then
            Sheets("EMEA input").Cells(lngRow, 2).EntireRow.Delete
        Else
            lngRow = lngRow + 1
        End If
    Loop

    subSpeedUp False
End Sub

Sub subSpeedUp(startStop As Boolean)
    If startStop Then
        Application.ScreenUpdating = False
        Application.DisplayStatusBar = False
        Application.Calculation = xlCalculationManual
        Application.EnableEvents = False
        ActiveSheet.DisplayPageBreaks = False
    Else
        Application.ScreenUpdating = True
        Application.DisplayStatusBar = True
        Application.Calculation = xlCalculationAutomatic
        Application.EnableEvents = True
    End If
End Sub

如果你有时间,你应该阅读这篇文章:http://msdn.microsoft.com/en-us/library/office/ff726673.aspx