我需要一个宏来查找此文本: “XYZ”和“*报告”
然后从XYZ选择行到*报告并删除包括选择在内的所有行。
我做到了这一点:
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
'我无法使用调整大小,因为从“XYZ”到“* .Report”的行数可以是8或9或任何其他内容。 '我可以删除特定的行,但不能删除从“XYZ”到“*报告”的范围。
答案 0 :(得分:2)
从您的代码中不清楚您是否在寻找部分匹配。
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
如果您尝试部分匹配,则MATCH functions可以轻松更改为通配符搜索。
答案 1 :(得分:2)
如果您已确定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和Report对,您可能需要在.Find中使用其他一些可选参数来获得健壮性。
如果有多对,那么您可能需要指定起点,并设置一个Do ...循环,当c和d为空时退出。
如果第一个XYZ可能在报告之后发生,您可能还需要检查以确保它们的顺序正确,否则错误的行将被删除。