VBA。如果一个单元格为空,则连续删除多个单元格

时间:2020-02-18 23:21:07

标签: excel vba delete-row

我在excel工作表中有多个列...例如A1:D10。 我想在C列中找到任何空白单元格,删除该单元格以及同一行的A,B和D单元格,然后向上移动。但仅在A1:D10范围内。我要在此excel工作表中的此范围之外的其他信息保留在其原始位置。因此,我不能使用这样的东西:

.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

我也无法像下面这样工作,因为它只会上移单列,而不是上移四列。

Set rng = Range("A1:D10").SpecialCells(xlCellTypeBlanks)
rng.Rows.Delete Shift:=xlShiftUp

3 个答案:

答案 0 :(得分:0)

如果第10行下方的AD列中没有 no 数据,而您不想向上移动,则SpecialCells和{{ 1}}可以这样使用

Delete Shift Up

如果第10行下方的Sub Demo1() Dim ws As Worksheet Dim TestColumn As Long Dim StartColumn As Long Dim EndColumn As Long Dim FirstRow As Long Dim LastRow As Long Dim i As Long Dim rng As Range, arr As Range ' set up reference data Set ws = ActiveSheet '<~~ update as required TestColumn = 3 'C StartColumn = 1 'A EndColumn = 4 'D FirstRow = 1 LastRow = 10 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual With ws On Error Resume Next Set rng = .Range(.Cells(FirstRow, TestColumn), .Cells(LastRow, TestColumn)).SpecialCells(xlCellTypeBlanks) On Error GoTo 0 If Not rng Is Nothing Then For Each arr In rng.Areas arr.EntireRow.Resize(, EndColumn - StartColumn + 1).Delete Shift:=xlShiftUp Next End If End With Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub A列中有您不想向上移动的数据,则可以使用DCut,像这样

Paste

答案 1 :(得分:0)

使用变体数组方法

Sub test2()
    Dim rngDB As Range, vDB As Variant
    Dim i As Integer, j As Integer, n As Integer
    Dim k As Integer

    Set rngDB = Range("a1:d10")

    vDB = rngDB

    n = UBound(vDB, 1)
    For i = 1 To n
        If IsEmpty(vDB(i, 3)) Then
            For j = 1 To 4
                If j <> 3 Then
                    vDB(i, j) = Empty
                End If
            Next j
        End If
    Next i
    For j = 1 To 4
        If j <> 3 Then
            For i = 1 To n - 1
                For k = i To n - 1
                    If vDB(k, j) = Empty Then
                        vDB(k, j) = vDB(k + 1, j)
                        vDB(k + 1, j) = Empty
                    End If
                Next k
            Next i
        End If
    Next j
    rngDB = vDB
End Sub

答案 2 :(得分:-1)

下面将通过在第3列中查找一个空白单元格并删除该行并仅向上移动该行来满足您的要求。

Sub deleteEmptyRow()
Dim i As Integer

    For i = 1 To 10
        If Cells(i, 3) = "" Then
            Range(Cells(i, 1), Cells(i, 4)).delete Shift:=xlUp
        End If
    Next i

End Sub
相关问题