Vba:如何根据单元格值删除行


您可以在 VBA 中使用以下语法根据单元格值删除行:

 Sub DeleteRowsByValue()

    Dim ws As Worksheet
    Set ws = ActiveSheet
  
    'clear existing filters
    On Error Resume Next
    ws.ShowAllData
    On Error GoTo 0
    
    'filter range where column 2 in range is equal to "East"
    ws.Range(" A1:C10 ").AutoFilter Field:=2, Criteria1:=" East "
  
    'delete rows that are visible
    Application.DisplayAlerts = False
    ws.Range(" A2:C10 ").SpecialCells(xlCellTypeVisible).Delete
    Application.DisplayAlerts = True
  
    'remove filter
    On Error Resume Next
    ws.ShowAllData
    On Error GoTo 0
  
End Sub

此特定宏删除A1:C10范围内 B 列值等于“Is”的所有行。

该宏使用以下步骤:

  • A1:C10应用筛选器以仅显示 B 列中的值为“Is”的行。
  • 然后删除所有可见单元格。
  • 然后取下过滤器。

这会删除范围A1:C10中 B 列中的值等于“Is”的所有行。

以下示例展示了如何在实践中使用此语法。

示例:使用 VBA 根据单元格值删除行

假设我们有以下数据集,其中包含有关各种篮球运动员的信息:

假设我们要从数据集中删除 Conference 列等于“East”的每一行。

我们可以创建以下宏来执行此操作:

 Sub DeleteRowsByValue()

    Dim ws As Worksheet
    Set ws = ActiveSheet
  
    'clear existing filters
    On Error Resume Next
    ws.ShowAllData
    On Error GoTo 0
    
    'filter range where column 2 in range is equal to "East"
    ws.Range(" A1:C10 ").AutoFilter Field:=2, Criteria1:=" East "
  
    'delete rows that are visible
    Application.DisplayAlerts = False
    ws.Range(" A2:C10 ").SpecialCells(xlCellTypeVisible).Delete
    Application.DisplayAlerts = True
  
    'remove filter
    On Error Resume Next
    ws.ShowAllData
    On Error GoTo 0
  
End Sub

当我们运行这个宏时,我们会收到以下输出:

请注意,会议列中值为“East”的所有行均已被删除。

注意Application.DisplayAlerts=False行告诉 VBA 不要显示删除可见行的过程,从而加快该过程。

其他资源

以下教程说明如何在 VBA 中执行其他常见任务:

VBA:如何对单元格应用条件格式
VBA:如何计算范围内的行数
VBA:如何计算具有特定文本的单元格

添加评论

您的电子邮箱地址不会被公开。 必填项已用*标注