Deleting some data using Excel VBA and ranges
I'm looking for some guidance with a task I have been set from my eager new boss!
I've got a list of error codes in a named range "List", and a list of specific error codes that need to be identified "Codes".
What I need is some VBA code that will will check "List" and if any code exists that isn't in the "Codes" list it will delete it. (So, if it's in the "codes" range it stays, otherwise it gets deleted).
Can anybody help me with this please?
So far I've got this code, but it only does the opposite and deletes the codes I want to keep!
Sub DeleteCodes()
Application.ScreenUpdating = False
Dim InRange As Range, CritRange As Range
Dim InCell As Range, CritCell As Range
Set InRange = Range("Data") ' all selected source cells
Set CritRange = Range("List") ' the named range of words to be excluded
For Each InCell In InRange.Cells
For Each CritCell In CritRange.Cells
If InCell = CritCell Then
InCell = "" ' blank it
Exit For ' exit inner for
End If
Next C开发者_如何学JAVAritCell
Next InCell
Application.ScreenUpdating = True
End Sub
Sub DeleteCodes()
Dim InRange As Range, InCell As Range
Dim CritRange As Range
Dim v, f As Range
Set InRange = Range("Data") ' all selected source cells
Set CritRange = Range("List") ' the named range of words to be excluded
Application.ScreenUpdating = False
For Each InCell In InRange.Cells
Set f = CritRange.Find(InCell.Value, , xlValues, xlWhole)
If f Is Nothing Then InCell.Value = ""
Next InCell
Application.ScreenUpdating = True
End Sub
Try:
Sub DeleteCodes()
Dim rCell As Range
Application.ScreenUpdating = False
For Each rCell In [List].Cells
If Application.WorksheetFunction.CountIf([Codes], rCell.Value) = 0 Then
rCell.Value = ""
Next rCell
Application.ScreenUpdating = True
End Sub
精彩评论