【问题标题】:Deleting some data using Excel VBA and ranges使用 Excel VBA 和范围删除一些数据
【发布时间】:2011-06-15 08:24:04
【问题描述】:

我正在为我热切的新老板安排的任务寻求一些指导!

我有一个命名范围“列表”中的错误代码列表,以及需要识别的特定错误代码列表“代码”。

我需要的是一些 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

【问题讨论】:

  • 请展示你到目前为止所做的事情。谢谢。
  • 嗨,亚当。我已经用当前代码编辑了这个问题,不幸的是,这与我所追求的相反!

标签: excel vba


【解决方案1】:
   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

【讨论】:

    【解决方案2】:

    试试:

    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
    

    【讨论】:

    • @Lance,你确定这是一个正确的编辑吗?我像 Tim 一样根据 OP 的代码解释了这个问题。
    • @Readfidy,是的,按照他的指示,而不是他的代码。他的代码搞砸了,蒂姆从中得到了启示。见第 3 段。 (如果你想重新编辑它,请继续,这次狩猎我没有狗)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-02
    • 2017-02-15
    • 1970-01-01
    • 2012-05-31
    • 2014-11-26
    • 1970-01-01
    相关资源
    最近更新 更多