2016-03-22 2 views
0

Я пытаюсь найти конкретное значение ячейки в столбце, если значение найдено, мне нужно удалить всю строку. Ниже приведен код, который у меня есть до сих пор. Я получаю глобальную ошибку в Range («X22: X» lastRow) .selection line.Найти значение и удалить целую строку

может кто-нибудь помочь и рассказать мне, где я иду не так.

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 
+0

'Range ("X22: X" и lastRow) .Select' вместо' Range. ("X22: X & lastRow") Select' – Ralph

+0

спасибо, что его сейчас работает, но не вычеркивание строки с этим значением ячейки – user3088476

+0

Метод find находит первый или последний в зависимости от направления не всех. Для этого вам нужно будет прокручивать назад по диапазону или фильтровать критерии и удалять видимые строки. См. [ЗДЕСЬ] (http://stackoverflow.com/questions/33744149/code-in-vba-loops-and-never-ends-how-to-fix-this) для различных методов. –

ответ

1

Я d хотел бы добавить альтернативное решение, которое может быть немного быстрее и поступает непосредственно от самих 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 
+0

@ Raplh это решение скважин - спасибо – user3088476

1

Вместо того чтобы использовать 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 
+0

спасибо, что работает – user3088476

0

Похоже, что получено несколько ответов, когда я рисовал решение. Я все равно отправлю его. Мы просто определяем диапазон, содержащий наши данные, и используем для цикла, чтобы проверить каждое значение в первом столбце.

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