VBA通过比较3个相邻行来删除多行

时间:2016-02-09 22:10:35

标签: excel vba excel-vba delete-row

我试图找出噪声数据并删除整行噪声数据。总共有79行数据和大约6-7个噪声数据,数据都是整数。为了定义噪声数据,我调暗3个变量:row1,row2,row3,并比较彼此之间差异的绝对值,如果Absolute(row1-row2)和Abslute(row2-row3)同时大于5 ,我会说row2是一个嘈杂的数据并删除整行。但是,我有应用程序或对象定义的错误问题。我试图用变量,变量,long,double调暗变量。它们都不起作用,也是同样的问题。

Sub project()
    Dim a As Long, row1 As Long, row2 As Long, row3 As Long
    Dim rKill As Range
    a = 2
    Do
        row1 = Cells(a, 2).Value
        row2 = Cells(a + 1, 2).Value
        row3 = Cells(a + 2, 2).Value
        If Abs(row1 - row2) > 5 And Abs(row2 - row3) > 5 Then
            If rKill Is Nothing Then
                Set rKill = Cells(a + 1, 2)
            Else
                Set rKill = Union(rKill, Cells(a + 1, 2))
            End If
        End If
        a = a + 1
    Loop Until deltat_value1 = 14700
    rKill.EntireRow.Delete
End Sub

问题如下:Application-defined or object defined error并发生在以下行:deltat_value3 = Cells(a + 2, 2).Value 然后我想这可能是因为我定义了太多变量。我改变了一点:

Sub project()
    Dim a As Long, row1 As Long, row2 As Long, row3 As Long
    Dim rKill As Range
    a = 2
    Do
        row1 = Cells(a, 2).Value
        row2 = Cells(a + 1, 2).Value
        If Abs(row1 - row2) > 5 And Abs(row2 - row3) > 5 Then
            row3 = Cells(a + 2, 2).Value
            If Abs(row2 - row3) > 5 Then
            If rKill Is Nothing Then
                Set rKill = Cells(a + 1, 2)
            Else
                Set rKill = Union(rKill, Cells(a + 1, 2))
            End If
        End If
        End If
        a = a + 1
    Loop Until deltat_value1 = 14700
    rKill.EntireRow.Delete
End Sub

但它仍然无法正常工作,这次同样的错误显示为该行:

row2 = Cells(a + 1, 2).Value

1 个答案:

答案 0 :(得分:0)

这样的事情不会完全符合您的要求吗?

Sub delMe()
  Dim i As Long, rng As Range
  i = 2 'change to the row you want to start
  While Len(Cells(i + 1, 2).Value)
    If Abs(Cells(i - 1, 2).Value - Cells(i, 2).Value) And Abs(Cells(i + 1, 2).Value - Cells(i, 2).Value) Then
      If rng Is Nothing Then Set rng = Rows(i) Else Set rng = Union(rng, Rows(i))
    End If
    i = i + 1
  Wend
  rng.Delete
End Sub

仍然:我不知道deltat_value1将如何在循环中改变?不会运行你的循环,直到它到达表格的末尾?