使用查找删除行

我试图从结果之前的单词修改行中删除行。 我试图使用查找命令,但我没有任何运气。 这是我尝试过的许多变化之一:

Sub FindandDelete() Modifications = Range("A1:A1200").Find("Modifications", LookIn:=xlValues) Res = Cells.Find("Results", LookIn:=xlValues) Range("Modifications:Results").Delete End Sub 

任何想法或build议?

尝试这个:

 Sub FindandDelete() Dim Modifications As Excel.Range Dim Res As Excel.Range Set Modifications = Range("A1:A1200").Find(What:="Modifications", LookIn:=xlValues) Set Res = Range("A1:A1200").Find(What:="Results", LookIn:=xlValues) If Not (Modifications Is Nothing) And Not (Res Is Nothing) Then ActiveSheet.Range(Modifications, Res).EntireRow.Delete 'ClearContents '<<edit to delete rows rather than just clear their contents End If End Sub 

使用行号略有不同:

 Sub FindandDeleteRows() Dim Modifications As Integer Dim Res As Integer Dim lookinRange As Range Set lookinRange = Excel.ThisWorkbook.ActiveSheet.Range("A1:A1200") If Not (lookinRange.Find(What:="Modifications", LookIn:=xlValues) Is Nothing) Then Modifications = lookinRange.Find(What:="Modifications", LookIn:=xlValues).Row End If If Not (lookinRange.Find(What:="Results", LookIn:=xlValues) Is Nothing) Then Res = lookinRange.Find(What:="Results", LookIn:=xlValues).Row End If ActiveSheet.Rows(Modifications & ":" & Res).ClearContents End Sub 

您的代码无法正常工作的两个主要原因:

  1. 您正在使用“Res”和“Results”来引用相同的variables。
  2. 您将单元格的值分配给variables,而不是find这些单元格的行数。

所以在这里你去:

 Sub FindandDelete() Modifications = Range("A1:A1200").Find("Modifications", LookIn:=xlValues).Row Res = Cells.Find("Results", LookIn:=xlValues).Row Range(Modifications & ":" & Res).Delete End Sub 

但是,如果没有find值,则会引发错误…


所以试试这个更精细,但更准确的技术:

 Sub SomeSub() 'Just to stay clean and make sure we're using the proper workbook/sheet wb = ThisWorkbook ws = wb.Sheets("YourSheet") 'Rename with your sheet's name columnOfInterest = 1 'Replace with the number of the column 'Find the last row of that column last = ws.Cells(ws.Rows.Count, columnOfInterest).End(xlUp).Row 'Loop from the first row to the last... For x = 1 To last 'And stop at the first thing that resembles "Results"... If ws.Cells(x, columnOfInterest) Like "*Results*" Then Res = x Exit For End If Next x 'Loop from the first row to the last... For x = 1 To last 'And stop at the first thing that resembles "Modifications"... If ws.Cells(x, columnOfInterest) Like "*Modifications*" Then Modif = x Exit For End If Next x If Res > 0 And Modif > 0 And Res > Modif Then 'Loop from "Results" to "Modifications" (backwards, indeed) to delete the rows For x = Res To Modif Step -1 ws.Rows(x).Delete Next x End If End Sub