jenit
asked on
Excel Macro - search for multiple values
I am trying to search column A for value AAS or ACC and if I find them keep those rows and delete everything else. the code I'm pasting works fine if there is only 1 value either AAS or ACC - so it is the OR component I'm having an issue with. Any help would be appreciated.
Dim rng As Range, cell As Range, del As Range
Set rng = Intersect(Range("A:A"), ActiveSheet.UsedRange)
For Each cell In rng
If (cell.Value) <> "AAS" Or (cell.Value) <> "ACC" Then
If del Is Nothing Then
Set del = cell
Else: Set del = Union(del, cell)
End If
End If
Next cell
On Error Resume Next
del.EntireRow.Delete
Dim rng As Range, cell As Range, del As Range
Set rng = Intersect(Range("A:A"), ActiveSheet.UsedRange)
For Each cell In rng
If (cell.Value) <> "AAS" Or (cell.Value) <> "ACC" Then
If del Is Nothing Then
Set del = cell
Else: Set del = Union(del, cell)
End If
End If
Next cell
On Error Resume Next
del.EntireRow.Delete
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
And a slightly more maintainable approach, making it easier to change the acceptable values to keep.
Dim rng As Range, cell As Range, del As Range
Dim KeepValues As String
KeepValues = "AAS,ACC"
Set rng = Intersect(Range("A:A"), ActiveSheet.UsedRange)
For Each cell In rng
If InStr(1, "," & KeepValues & ",", "," & cell.Value & ",", vbTextCompare) = 0 Then
If del Is Nothing Then
Set del = cell
Else
Set del = Union(del, cell)
End If
End If
Next cell
On Error Resume Next
del.EntireRow.Delete
~bp
One of the possible reasons is that in VB when you compare texts it compare case sensitivity..The way you set it up it doesn't check for that..the way i will do this to ensure no matter what the case it does it job was like this..
Saurabh...
Dim rng As Range, cell As Range, del As Range
Set rng = Intersect(Range("A:A"), ActiveSheet.UsedRange)
For Each cell In rng
If InStr(1, cell.Value, "aas", vbTextCompare) = 0 And InStr(1, cell.Value, "acc", vbTextCompare) = 0 Then
If del Is Nothing Then
Set del = cell
Else: Set del = Union(del, cell)
End If
End If
Next cell
On Error Resume Next
del.EntireRow.Delete
Saurabh...
In the original, if you change the OR for an AND, it will solve the problem.
This means it doesn't equal "ASC" AND it doesn't equal "ACC" so it must be something else.
This means it doesn't equal "ASC" AND it doesn't equal "ACC" so it must be something else.
ASKER
Simple and easy. Thanks all. I didn't try all the solutions as simply adding the NOT, () and change <> to = worked. Sorry it took so long for me to get back. We had a major client issue that put all other things on total HOLD.
All is resolved now including my macro challenge.
LOVE the help available out here!!!
All is resolved now including my macro challenge.
LOVE the help available out here!!!
Open in new window