如果单元格为空,则删除工作表

时间:2015-09-24 05:43:07

标签: excel vba excel-vba

这将是一个非常简单的问题。 但我不确定为什么这不适用于我的excel vba代码。

Sheets("I- ABC").Select
If IsEmpty(Range("A3").Value) = True And _
    IsEmpty(Range("A4").Value) = True And _
    IsEmpty(Range("A5").Value) = True And _
    IsEmpty(Range("A6").Value) = True Then
    Sheets("I- ABC").Delete
End If

5 个答案:

答案 0 :(得分:0)

你得到什么类型的错误?我尝试了这段代码,Excel只显示警告信息:

Warning message

您可以添加以下内容来避免此消息:

Application.DisplayAlerts = False

Application.DisplayAlerts = True

分别在代码的开头和结尾。

- 编辑代码

Sub Example()

Application.DisplayAlerts = False

With Sheets("I- ABC")
    If Application.WorksheetFunction.CountA(.Range("A3:A6")) = 0 Then
        .Delete
    End If
End With

Application.DisplayAlerts = True

End Sub

答案 1 :(得分:0)

尝试与此相似

Sub Test()
    Application.DisplayAlerts = False
    With Sheets("Sheet1")
     Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    End With
    Application.DisplayAlerts = True
End Sub

PS:它适用于我并删除“A:A``

中包含空单元格的行

@Tim Williams建议的方法在我的情况下也按照以下代码为我工作

Sub Test6()
  Dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A3:A6")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

即使我们使用Application代替WorksheetFunction

,它仍然有效

答案 2 :(得分:0)

如果If Application.CountA(Range("A3:A6")) = 0 Then没有像蒂姆建议那样工作那么这意味着单元格有空格或不可打印的字符。

试试这个

Sub Sample()
    Dim pos As Long

    With Sheets("I- ABC")
        pos = Len(Trim(.Range("A3").Value)) + _
              Len(Trim(.Range("A4").Value)) + _
              Len(Trim(.Range("A5").Value)) + _
              Len(Trim(.Range("A6").Value))

        If pos = 0 Then
            Application.DisplayAlerts = False
            .Delete
            Application.DisplayAlerts = True
        Else
            MsgBox "The cells are not empty"
        End If
    End With
End Sub

答案 3 :(得分:0)

随着skkakkar的想法扩大。

Sub Hello()
    Dim rng As Range
    Application.DisplayAlerts = 0
    On Error GoTo er
    Set rng = Range("A3:A6").SpecialCells(xlCellTypeConstants, 23)
    Exit Sub
er:     MsgBox "ActiveSheet.Delete" 'delete sheet
End Sub

答案 4 :(得分:0)

如果空格是问题,那么您可以尝试以下代码:

Public Sub RemoveIfEmpty()

    Application.DisplayAlerts = False

    With Sheets("I- ABC")
        If Trim(.Range("A3") & .Range("A4") & .Range("A5") & .Range("A6")) = "" Then
            .Delete
        End If
    End With

    Application.DisplayAlerts = True

End Sub
相关问题