在Excel中使用VBA进行搜索时删除内容

问题描述:

我试图用宏删除Excel中某个单词/短语后面的数据。在Excel中使用VBA进行搜索时删除内容

问题是单元格位置可能因报表运行/导出后电子表格中有多少行而异。如果可能的话,我需要一个解决方案来针对某个短语(使用我推测的查找功能),并从文本可能出现的位置删除30个单元格(无cet单元格)。

这可能吗?

这是可能的,但你想要的细节不是最清楚的。这里有一些代码可以帮助你开始。它会在工作表上的所有单元格中查找给定的短语。如果发现它,它会将该单元下面的30个单元添加到将要删除的组中。一旦它搜索到所有单元格,它将删除收集的组。

由于我们遍历要从中删除的集合,我收集要删除的单元格(使用Union)并在循环关闭后删除它们。

这可能不是最快的代码,因为它搜索UsedRange中的所有单元格,但它应该适用于大多数用途。

Sub deleteBelowPhrase() 

    Dim cell As Range 
    Dim sht As Worksheet 

    Dim phrase As String 
    Dim deleteRows As Integer 

    'these are the parameters 
    phrase = "DELETE BELOW ME" 
    deleteRows = 30 

    'assumes you are searching the active sheet 
    Set sht = ActiveSheet 

    Dim del_range As Range 
    Dim del_cell As Range 

    For Each cell In sht.UsedRange 

     'check for the phrase in the cell 
     If InStr(cell.Value2, phrase) > 0 Then 

      'get a reference to the range to delete 
      Set del_cell = sht.Range(cell.Offset(1), cell.Offset(deleteRows)) 

      'create object to delete or add to existing 
      If del_range Is Nothing Then 
       Set del_range = del_cell 
      Else 
       Set del_range = Union(del_range, del_cell) 
      End If 
     End If 

    Next cell 

    'delete the block of cells that are collected 
    del_range.Delete xlShiftUp 

End Sub 

之前

before

after