-2

我有一个 Excel 宏,可以删除 Excel 工作表中的所有空行。此宏需要很长时间才能完成。这些文件是自动生成的,每个文件都需要运行这个宏。宏在检查其值后一次删除一行。

我需要这样的东西:

If  rowValue = "" then
    deleteThisRow And deleteAll Subsequent rows at once
End If

这是我现在使用的代码:

Sub RemoveRows()
    Range("A8").Select 
    Dim checkval 
    Dim RowAmount
    RowAmount = 93

    Do
        checkval = ActiveCell.Value
        If (checkval = "") Then
            ActiveCell.EntireRow.Delete
        Else
            ActiveCell.Offset(1, 0).Select
        End If
        RowAmount = RowAmount - 1
    Loop While RowAmount > 0
End Sub
4

2 回答 2

1

您在一次操作中删除所有必要行的想法很成功。此外,避免Select和避免在一系列单元格上循环也会加快速度。

这是一种适合您的方法

Sub Demo()
    Dim sh As Worksheet
    Dim rng As Range
    Dim rngBlanks As Range

    ' Get a reference to the sheet you want to process
    Set sh = ActiveSheet

    ' Get a reference to the range of cells to test
    With sh
        Set rng = .Range(.Cells(8, 1), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    ' if there are no blanks SpecialCells will error, so handle it
    On Error Resume Next
    ' Reduce rng to reference only blank cells
    Set rngBlanks = rng.SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0

    ' see if there are any blanks
    If Not rngBlanks Is Nothing Then
        ' delete all of them
        rngBlanks.EntireRow.Delete
    End If
End Sub

根据提供的其他信息进行更新:“空白”单元格可能包含返回空字符串的公式。

这是一种使用方法AutoFilter

Sub Demo()
    Dim sh As Worksheet
    Dim rng As Range
    Dim rngBlanks As Range

    Application.ScreenUpdating = False
    ' Get a reference to the sheet you want to process
    Set sh = ActiveSheet

    ' Get a reference to the range of cells to test, plus header row
    With sh
        Set rng = .Range(.Cells(7, 1), .Cells(.Rows.Count, 1).End(xlUp))
    End With

    ' Apply filr to hide non-empty cells
    sh.AutoFilterMode = False
    rng.AutoFilter Field:=1, Criteria1:="=", VisibleDropDown:=True

    ' if there are no blanks SpecialCells will error, so handle it
    On Error Resume Next
    ' Reduce rng to reference only blank cells, exclude header row
    Set rngBlanks = rng.Offset(1, 0).SpecialCells(xlCellTypeVisible)
    On Error GoTo 0

    ' see if there are any blanks
    If Not rngBlanks Is Nothing Then
        ' delete all of them
        rngBlanks.EntireRow.Delete
    End If

    sh.AutoFilterMode = False
    Application.ScreenUpdating = True
End Sub
于 2013-04-10T09:05:53.653 回答
0

所以基本上,如果它遇到一个空白行,它应该删除该行及其下面的所有行。

要删除下面的所有行,您基本上可以执行按 CTRL 和向下箭头时发生的相同操作 - 它转到下一个值(如果有,在您的情况下听起来不会是)或到最后(第 65536 行是我遇到的所有 Excel 版本的限制)。这将是...

Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlUp

这将从您选择的行开始(因此无需删除它),一直到下一个值或末尾,然后删除所有这些行。

编辑 - 整个宏:

Dim i As Integer
For i = 1 To 93
    Range("A" & i).Select
    Dim CheckVal As String
    CheckVal = ActiveCell.Value
    If (CheckVal = "") Then
        Range(Selection, Selection.End(xlDown)).Select
        Selection.Delete Shift:=xlUp
    End If
Next i

但请记住,如果在找到的第一个“空白”下方有任何值,它们也会作为第一个连续值被删除。

于 2013-04-10T08:24:36.597 回答