如何删除部分数组?

时间:2016-04-24 17:50:36

标签: vba excel-vba access-vba excel

我正在处理的程序涉及从excel中读取并确定i - (i + 1)和i-(i-1)之间的差异。

如果差异超过4,则程序将删除i处的行。

该程序在第一次尝试时效果很好。突然间,它说“你不能改变数组的一部分”。

Option Explicit

Sub Data_Delet()

    Dim a As Double, b As Double, c As Double, i As Double
    Dim rkill As Range
    ' a,b, and c are used as steps in order to proceed to the next data points
    a = 18
    b = 0
    c = 0

    With ThisWorkbook.Worksheets("Sheet1")

        ' The second do loop delete data points that does not follow the requirements
        Do
        If Abs(.Cells(a - 1, 2) - .Cells(a, 2)) > 4 And Abs(.Cells(a, 2) - .Cells(a + 1, 2)) > 4 Then
             If rkill Is Nothing Then
                Set rkill = Rows(a)
             Else
                Set rkill = Union(rkill, Rows(a))
             End If
        End If
        a = a + 1
        Loop Until .Cells(a, 2).Value = ""
        If Not rkill Is Nothing Then rkill.EntireRow.Delete
     ' The third Do loop determines the number of data points that are still present after deleting the data points
      Do
        i = .Cells(17 + c, 1)
        c = c + 1
    Loop Until .Cells(17 + c, 1).Value = ""

  ' The if statment determine whether or not the number data points from before are the same after deletion process
     If b = c Then
     .Cells(2, 5) = "N"
     Else
     .Cells(2, 5) = "Y"
     End If

      ' c is the number of data point after deletion
     .Cells(12, 5) = c

    End With

End Sub

1 个答案:

答案 0 :(得分:2)

rkill.EntireRow.Delete上的错误“您无法更改数组的一部分”意味着您要删除的行与数组公式中引用的范围相交(带括号的公式) 。

Excel不允许这样做。一种方法是在代码开头删除有问题的数组公式,并在代码末尾再次重新定义它们。或者找到一个解决方案将这些数组公式转换为普通公式。