遍历范围内的每个单元格

时间:2018-09-23 08:57:32

标签: excel vba excel-vba

我正在编写一个程序,用于删除“带空单元格的选择”中的行。我编写了代码,效果很好,但是有缺陷。

代码为:

    Dim i As Integer
    Dim j As Integer
    Dim Num As Integer
    Num = Selection.Cells.Count
    'MsgBox ("Num of Cells " & Num)
     Selection.End(xlUp).Select
    If (IsEmpty(ActiveCell)) Then
        Selection.End(xlDown).Select
    End If
    For i = 1 To Num
        If (IsEmpty(ActiveCell)) Then
            ActiveCell.Offset(1, 0).Select
            ActiveCell.Offset(-1, 0).EntireRow.Delete
            ActiveCell.Offset(-1, 0).Select
            Num = Num - 1
            On Error GoTo Last
        Else
            ActiveCell.Offset(1, 0).Select
        End If
    Next

Last:
    Exit

现在,我试图通过循环Range中的单元而不是上面的For循环来重写代码:

    Dim i As Integer
    Dim j As Integer
    Dim Num As Integer
    Dim myRange As Range
    ActiveSheet.Select
    Set myRange = Selection.Cells
        For Each myRange In Selection
        If (IsEmpty(myRange)) Then
            ActiveCell.EntireRow.Delete
            On Error GoTo Last
        Else
            'ActiveCell.Offset(1, 0).Select
        End If
    Next myRange

Last:
    Exit

这段代码无法正常工作。请提出您的建议并更正守则

3 个答案:

答案 0 :(得分:0)

您可以尝试

If WorksheetFunction.CountBlank(Selection) > 0 Then Intersect(Selection.SpecialCells(xlCellTypeBlanks).EntireRow, Selection.Columns(1)).EntireRow.Delete

答案 1 :(得分:0)

Specialalcells似乎易于使用。

Sub test()
    Dim rngDB As Range
    Set rngDB = Selection

    On Error Resume Next
    Set rngDB = rngDB.SpecialCells(xlCellTypeBlanks)

    If Err.Number = 0 Then
        rngDB.EntireRow.Delete
    End If
End Sub

答案 2 :(得分:0)

这里是避免依赖SelectionSelect的选项。

您可以使用InputBox确定范围。这将使您能够正确限定所有范围/工作表。然后,您可以遍历所选范围并确定是否应删除行(如果为空白)。

最后,一次删除所有行。在较大的操作上,这将更快,因为您只有1个删除实例,而是在循环中连续删除行。

Option Explicit

Sub Blanks()

Dim MyRange As Range, MyCell As Range, DeleteMe As Range
Set MyRange = Application.InputBox("Select Range", Type:=8)

For Each MyCell In MyRange
    If MyCell = "" Then
        If DeleteMe Is Nothing Then
            Set DeleteMe = MyCell
        Else
            Set DeleteMe = Union(DeleteMe, MyCell)
        End If
    End If
Next MyCell

If Not DeleteMe Is Nothing Then DeleteMe.EntireRow.Delete

End Sub