2011-06-14 91 views
0

我正在寻找一些指导,我已经从我渴望的新老板设置了一个任务!使用Excel VBA和范围删除一些数据

我已经列出了命名范围“List”中的错误代码,以及需要标识“Codes”的特定错误代码列表。

我需要的是一些将检查“列表”的VBA代码,如果有任何代码不在“代码”列表中,它将删除它。 (所以,如果它在它的“代码”范围内,否则它会被删除)。

有人可以帮我吗?

到目前为止,我已经得到了这段代码,但它只是做了相反的事,并删除了我想保留的代码!

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 CritCell 
    Next InCell 

    Application.ScreenUpdating = True 
End Sub 
+0

敬请显示到目前为止你做了什么。谢谢。 – bernie 2011-06-14 17:13:55

+1

嗨,亚当。我用当前的代码编辑了这个问题,但不幸的是,它只是与我之后的相反! – tonypreece 2011-06-14 17:20:51

回答

2
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 
1

尝试:

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

@兰斯,你确定这是一个正确的编辑?我将这个问题解释为Tim所做的,并且基于OP的代码。 – Reafidy 2011-06-15 00:36:07

+0

@Readfidy,是的,根据他的指示,而不是他的代码。他的代码混乱了,Tim从中得到了启发。见第3段。 (如果你想编辑它,继续,我没有狗在这个狩猎)。 – 2011-06-15 06:16:27

+0

好的。将离开,谢谢。 – Reafidy 2011-06-15 06:30:23