0

I have certain values in my column A.

For exapmple:

Header
A
A
C
C
D
D
E
F

I want to keep rows having D and remove all other. As a first step, Have sorted my sheet. Now trying below code but its giving error of

Invalid or unqualified reference

Dim strA As Range
Dim strB As Range

    Range("A:A").Select
    Selection.Find(What:="D", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate
    ActiveCell.Offset(-1, 0).Select
    Set strA = .ActiveCell


    Range(Selection, Selection.End(xlUp)).Select
    Range(Selection, ActiveCell.Offset(1, 0).Select).Select
    ActiveCell.Offset(1, 0).Select
    Set strB = .ActiveCell

    Range(strA, strB).Select

End Sub
Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73

1 Answers1

0

Maybe something like this :

Sub test()
n = Application.WorksheetFunction.CountIf(Range("A:A"), "D")
Set c = Range("A:A").Find("D", lookat:=xlWhole)
Range("A" & c.Row, Range("E" & c.Row).Offset(n - 1, 0)).Copy Destination:=Range("A2") 'change E as needed, depends how many column is your data
Set rngDel = Range("A1").Offset(n + 1, 0)
Range(rngDel, rngDel.End(xlDown)).EntireRow.Delete
End Sub

Before running the code, the data table must be sort first by column A.
The code will count how many "D" are there in column A.
Then it get the cell where it find the first "D"
From there it copy all the cells which has "D" value
then paste it to cell A2
lastly, it delete the remaining cells which doesn't have "D" value

karma
  • 1,999
  • 1
  • 10
  • 14