查找特定文本并删除其上方的三行

时间:2016-07-12 20:57:25

标签: excel excel-vba vba

我的宏遇到了一些麻烦,我想我会再次向宏观专家询问一些帮助。

我需要帮助找到一行中的某些文本并删除它上面的三行,取消循环。 这就是我一直在使用它并且它无法正常工作。 Image of: What I need deleted and the required end result. Also the Macros that I'm using

Sub Delete_Rows()

Dim x
For x = Cells(Rows.Count, ActiveCell.Column).End(xlUp).Row To ActiveCell.Row Step -1
    If Cells(x, 1) = "TOT" Then 
        Cells(x, 1).EntireRow.Delete      
        Cells(x - 1, 1).EntireRow.Delete  
        Cells(x - 2, 1).EntireRow.Delete  
        Cells(x - 3, 1).EntireRow.Delete  
End If

End Sub

我也在网上浏览过这个常见问题的其他解决方案,但没有任何方法可以帮助我。我需要这个宏可以在Excel工作簿的任何页面中使用。

非常感谢你们!

3 个答案:

答案 0 :(得分:1)

为什么要制作循环?为什么不选择自动的东西?

Sub Delete_Rows()
    Const WordToLook = "TOT"
    Dim RowWord As Long
    RowWord = Columns(3).Find(WordToLook, LookAt:=xlWhole).Row
    Rows(RowWord - 3 & ":" & RowWord - 1).Delete
End Sub

答案 1 :(得分:0)

这将找到" TOT"在工作表中的任何位置删除它上面的3行。

Sub Delete()
Dim find As String: find = "TOT"
Dim rng As Range

Set rng = Sheets("Sheet1").Cells.find(What:=find, After:=Sheets("Sheet1").Cells(1, 1), LookIn:=xlValues, Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True)

If Not rng Is Nothing Then
  rng.EntireRow.Delete
  rng.Offset(-1).EntireRow.Delete
  rng.Offset(-2).EntireRow.Delete
  rng.Offset(-3).EntireRow.Delete
End If

End Sub

答案 2 :(得分:0)

如果我理解正确,下面的编辑应该有帮助

Sub Delete_Rows()

Dim xRow As Integer
Dim strSearch As String

strSearch = "TOT"
' Assuming Total is in column C as your picture shows, but you can configure to search anywhere

xRow = Range("C" & Rows.Count).End(xlUp).Row
Range("$C1:C" & xRow).Select

Selection.Find(What:=strSearch, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Select

Range(ActiveCell.Row & ":" & ActiveCell.Offset(-3, 0).Row).Select
Selection.Delete Shift:=xlUp

End Sub