VBA 如果单元格为空则删除行

VBA delete row if cell is empty

我有一个宏可以从数据集中过滤和删除不必要的数据并创建一个数据透视表 table。 过滤删除数据的代码如下:

For i = 2 To LastRowG
If Range("G" & i).Value = "APGCVGP" Then

    lo.Range.autofilter Field:=7, Criteria1:="APGCVGP"
    
    Application.DisplayAlerts = False
       lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
    Application.DisplayAlerts = True
    
    lo.autofilter.ShowAllData
    Else
    End If

Next i

如何使用此格式删除特定列中包含空白单元格的行?

我尝试了以下方法,但没有任何反应:

For i = 2 To LastRowG
If Range("G" & i).Value = "=" Then

    lo.Range.autofilter Field:=7, Criteria1:="="
    
    Application.DisplayAlerts = False
       lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
    Application.DisplayAlerts = False
    
    lo.autofilter.ShowAllData
    Else
    End If

Next i

我尝试了相同的代码,但使用 "<>" 而不是 "=",但也没有做任何事情。

不是你第一个过程中的循环,你不能像这样避免它吗?

If WorksheetFunction.CountIf(Range("G:G"),"APGCVGP") Then
    lo.Range.autofilter Field:=7, Criteria1:="APGCVGP"
    Application.DisplayAlerts = False
       lo.DataBodyRange.SpecialCells(xlCellTypeVisible).Delete
    Application.DisplayAlerts = True
    lo.autofilter.ShowAllData
End If

对于您的第二个程序,您将使用

测试空白
If Range("G" & i).Value = "" Then

但是,同样,我认为您不需要循环,即如果 G2 为空白,那么您将删除所有空白单元格,但是,在循环的下一次迭代中,如果 G3 也为空白,您将是试图再次删除您已经删除的单元格... 无论如何,您不需要过滤器来识别空白,即

lo.DataBodyRange.Columns(7).SpecialCells(xlCellTypeBlanks).Rows.Delete

如果您只想根据 g 列中的值为空或等于 '' 的值删除整行,那么这应该可行。请注意,在最后删除行比在循环时删除行效率更高,也是更好的做法。

在 运行 任何代码之前请小心保存您的工作,因为我们看不到您真正在做什么。

Sub deleteSomeRows()
   Dim i As Long, killRange As Range, aCell As Range
   
   
   For i = 2 To LastRowG
   Set aCell = Range("G" & i)
      
      If aCell.Value = "" Then
         If killRange Is Nothing Then
            Set killRange = aCell.EntireRow
         Else
            Set killRange = Union(killRange, aCell.EntireRow)
         End If
      End If
   
   Next i
   
   If Not killRange Is Nothing Then
      killRange.ClearContents
      killRange.Delete (xlUp)
   End If
End Sub