Excelmacros查找文本,并从中select行

我需要一个macros来find这个文本:“XYZ”和“* Report”

然后从XYZselect行到*报告并删除包括select的所有行。

我已经这样做了:

Sub DelWordsCol() Dim c As Range Dim d As Range Dim SrchRng Set SrchRng = ActiveSheet.Range("A1", ActiveSheet.Range("A65536").End(xlUp) Do set c=SrchRng.Find("XYZ", LookIn:=xlValues) if not c Is Nothing Then c.EntireRow.Delete Loop while Not c Is Nothing Do set d=SrchRng.Find("*Report", LookIn:=xlValues) if not d Is Nothing Then d.EntireRow.Delete Loop while Not c Is Nothing End Sub 

'我不能使用resize从“XYZ”到“*。报表”可以是8或9或任何其他行。 '我可以删除特定的行,但不能从“XYZ”到“* Report”的范围。

如果您已经确定了c和d,那么只需使用这两个单元格来定义和删除范围:

 Option Explicit Sub DelRange() Dim c As Range Dim d As Range Const lSrchCol As Long = 1 'searching column A With ActiveSheet.Columns(lSrchCol) Set c = .Find(what:="XYZ", LookIn:=xlValues) Set d = .Find(what:="*Report", LookIn:=xlValues) End With If Not c Is Nothing And Not d Is Nothing Then _ Range(c, d).EntireRow.Delete End Sub 

如果列中可能有多个单独的XYZ和报表对,则可能需要使用.Find中的其他一些可选参数来提高可靠性。

如果有多个对,那么你可能需要指定你的起点,并设置一个Do …循环,当c和d什么都不是的时候退出。

如果第一个XYZ可能报告之后出现,则可能还需要检查以确保它们的顺序正确,否则错误的行将被删除。

从你的代码中不清楚你是否在寻找部分匹配。

 Sub DelWordsCol() Dim c As Long, d As Long Dim strA As String, strB As String strA = "XYZ" strB = "Report" With Worksheets("Sheet4") '<~~ set this worksheet reference properly! With Intersect(.Columns(1), .UsedRange) 'shift one row down off the header row With .resize(.rows.count - 1, 1).offset(1, 0) Do While Not IsError(Application.Match(strA, .Cells, 0)) c = Application.Match(strA, .Cells, 0) If Not IsError(Application.Match(strB, .Cells.Offset(c, 0), 0)) Then d = Application.Match(strB, .Cells.Offset(c, 0), 0) .Cells(c, 1).Resize(d + 1, 1).EntireRow.Delete Else Exit Do End If Loop End With End With End With End Sub 

如果您尝试进行部分匹配,则MATCHfunction可以轻松更改为通配符search。