退出 if 语句而不退出 sub

Exiting if statement without exiting sub

我有一个 VBA 代码可以删除空单元格,允许列中更靠下的数据向上移动到顶部。有两件事我想解决。一,我不想退出 sub,我想退出 if 语句。我读过您可以退出循环、while、fors 等,但不能退出 ifs。我不想退出 sub,因为我的 sub 中有更多代码。有什么建议吗?

如果列顶部已经有数据,我在代码中添加另一行到 运行 时也会遇到问题。

    Sub Remove_Empties ()

    Dim Last as Long
    Dim Mcol as Range

    Last = Cells(Rows.Count, "AD").End(xlUp).Row
    If Last = 1 Then Exit Sub 'no value only header in row 1
    'otherwise
    Set Mcol = Range("AD2:AD" & Last) 'contains any value
    Application.ScreenUpdating = True
    Mcol.SpecialCells(xlCellTypeBlanks).Delete xlUp
    Application.ScreenUpdating = True

    End Sub

我希望它能够运行以下三种情况。第一个包含 header 下方行中的数据。第二个有几个空单元格。第三个单元格全部为空。 1 不应更改,2 应更改以匹配 1 的格式,而 3 不应执行任何操作。 2和3可以用上面的代码完成,但是1不行。

    1         2         3
    A       
    B  
    C         A
    D         B
              C
              D

可能是这样的,注意以下几点:

  • 您不需要 Application.ScreenUpdating = True 行。你或许可以摆脱两者。
  • 您需要处理没有空白单元格(第 1 列)的可能性。

Sub Remove_Empties()

    Dim Last As Long
    Last = Cells(Rows.Count, "AD").End(xlUp).Row

    If Last <> 1 Then
        Dim Mcol As Range
        Set Mcol = Range("AD2:AD" & Last) 'contains any value

        Dim cellsToDelete As Range

        On Error Resume Next
        Set cellsToDelete = Mcol.SpecialCells(xlCellTypeBlanks)
        On Error GoTo 0

        If Not cellsToDelete Is Nothing Then
            cellsToDelete.Delete shift:=xlUp
        End If
    End If

End Sub

或略微压缩:

Sub Remove_Empties()

    Dim Last As Long
    Last = Cells(Rows.Count, "AD").End(xlUp).Row

    If Last <> 1 Then
        On Error Resume Next
        Range("AD2:AD" & Last).SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp
        On Error GoTo 0 
    End If

End Sub

我将添加另一个您可以在您的逻辑(代码)中使用的答案。使用简单的 GoTo 语句将跳出 If。例如:

Sub UsingGoTo()

    If Last = 1 Then
        'do something
        GoTo CheckComplete
    Else
        'if not maybe exit sub?
        Exit Sub
    End If

CheckComplete:
    'continue with program

End Sub