2015-04-02 103 views
0

我試圖用宏刪除Excel中某個單詞/短語後面的數據。在Excel中使用VBA進行搜索時刪除內容

問題是單元格位置可能因報表運行/導出後電子表格中有多少行而異。如果可能的話,我需要一個解決方案來針對某個短語(使用我推測的查找功能),並從文本可能出現的位置刪除30個單元格(無cet單元格)。

這可能嗎?

回答

0

這是可能的,但你想要的細節不是最清楚的。這裏有一些代碼可以幫助你開始。它會在工作表上的所有單元格中查找給定的短語。如果發現它,它會將該單元下面的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