查找值并删除整行

我想在列中search特定的单元格值,如果find值,那么我需要删除整个行。 下面是我到目前为止的代码,我得到范围(“X22:X”&lastRow)。select线上的全局错误。

任何人都可以帮助,并告诉我我要去哪里错了。

Dim LResult As String Set sht1 = ThisWorkbook.Worksheets("Formatted") lastRow = Cells(Rows.Count, x).End(xlUp).Row 'MsgBox "Last Row: " & lastRow 'Used to check that the find LastRow worked Range("X22:X" & lastRow).Select Cells.Find(What:="1: Request").Select Selection.EntireRow.Delete 

我想添加一个替代解决scheme,它可能会更快一些,并直接来自Microsoft自己: https : //msdn.microsoft.com/en-us/library/office/ff839746.aspx

 Option Explicit Public Sub RemoveMatchingRows() Dim rngFound As Range Dim sht1 As Worksheet Set sht1 = ThisWorkbook.Worksheets("Formatted") With sht1.Range("X:X") Set rngFound = .Find(What:="1: Request") If Not rngFound Is Nothing Then While Not rngFound Is Nothing sht1.Rows(rngFound.Row).EntireRow.Delete Set rngFound = .FindNext Wend End If End With End Sub 

而不是使用查找,尝试使用if循环

解决scheme在这里find: http : //www.rondebruin.nl/win/s4/win001.htm

我只是调整它以适应你所提供的信息

 Sub Loop_Example() Dim Firstrow As Long Dim Lastrow As Long Dim Lrow As Long Dim CalcMode As Long Dim ViewMode As Long With Application CalcMode = .Calculation .Calculation = xlCalculationManual .ScreenUpdating = False End With With Sheets("Formatted") 'select the sheet so we can change the window view .Select 'If you are in Page Break Preview Or Page Layout view go 'back to normal view, we do this for speed ViewMode = ActiveWindow.View ActiveWindow.View = xlNormalView 'Turn off Page Breaks, we do this for speed .DisplayPageBreaks = False 'Set the first and last row to loop through Firstrow = .UsedRange.Cells(1).Row Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row 'We loop from Lastrow to Firstrow (bottom to top) For Lrow = Lastrow To Firstrow Step -1 'We check the values in the A column in this example With .Cells(Lrow, "A") If Not IsError(.Value) Then If .Value = "1: Request" Then .EntireRow.Delete 'This will delete each row with the Value "1: Request" 'in Column A, case sensitive. End If End With Next Lrow End With ActiveWindow.View = ViewMode With Application .ScreenUpdating = True .Calculation = CalcMode End With End Sub 

看起来像是在我草拟解决scheme时得到的一些答案。 无论如何,我会发布它。 我们只是定义包含我们的数据的范围,并利用for循环来检查第一列的每个值。

 Public Sub rmv() 'first define the String that we are looking for Dim searc As String searchTerm = "foo" 'define the sheet we operate on Set sht1 = ThisWorkbook.Worksheets("Sheet1") 'find last row lastRow = sht1.Cells(Rows.Count, "B").End(xlUp).Row ' 'MsgBox "Last Row: " & lastRow 'Used to check that the find LastRow worked ' Define the range of data Dim fRange As Range Set fRange = sht1.Range("B2:B" & lastRow) ' modify this range according to your own needs ' Loop through each row of the data range Dim i As Integer For i = 1 To fRange.Rows.Count: If fRange(i, 1) = searchTerm Then ' here we check the first cell of the range ' this row contains the wanted data => remove entire row fRange.Rows(i).EntireRow.Delete End If Next i End Sub