Excel VBA - redim arr时类型不匹配

时间:2018-01-10 01:20:28

标签: arrays excel vba excel-vba

我有一个动态数组,其中值来自工作表。 如果条件满足,我想删除符合条件的元素。代码来自this post,但它正在返回

  

类型不匹配

on ReDim Preserve arr(Len(arr) - 1)

Sub arrtest()
Dim arr As Variant
Dim i As Integer

ReDim arr(1 To 1)

Dim cnt As Long
cnt = 0

For i = 1 To Cells(Rows.Count, "L").End(xlUp).Row

    If Cells(i, "A").Value = "-2" Then
        cnt = cnt + 1
        ReDim Preserve arr(1 To cnt)
        arr(cnt) = Cells(i, "A").Value
    End If

Next i

    For i = 1 To cnt
        Debug.Print "This is arr: "; arr(i)

     If arr(i) = "TEST" Then
      Call DeleteElementAt(i, arr)
      Debug.Print "This is new arr: "; arr(i)
      Else
      Debug.Print "Nothing is deleted"
      End If
    Next

End Sub

Public Sub DeleteElementAt(ByVal index As Integer, ByRef arr As Variant)
       Dim i As Integer

        ' Move all element back one position
        For i = index + 1 To UBound(arr)
            arr(i - 1) = arr(i)
        Next
        ' Shrink the array by one, removing the last one
        ReDim Preserve arr(Len(arr) - 1)
End Sub

1 个答案:

答案 0 :(得分:3)

数组的Len(或长度)是其上边界。要将数组的大小减小1,

ReDim Preserve arr(UBound(arr) - 1)

相反,数组的开头是LBound或下边界。这通常为0(零)或1(一),在二维数组中,您可以指定等级。