删除VBA数组的第一个元素

有没有办法删除VBA中的数组的第一个元素?

像JavaScript的shift()方法?

 Option Explicit Sub Macro1() Dim matriz() As Variant Dim x As Variant matriz = Array(0) ReDim Preserve matriz(1) matriz(1) = 5 ReDim Preserve matriz(2) matriz(2) = 10 ReDim Preserve matriz(3) matriz(3) = 4 ReDim Preserve matriz(1 To UBound(matriz)) For Each x In matriz Debug.Print x Next x End Sub 

这是returing错误:下Subscript out of range

在VBA中没有直接的方法,但可以像这样轻松地删除第一个元素:

 'Your existing code '... 'Remove "ReDim Preserve matriz(1 To UBound(matriz))" For i = 1 To UBound(matriz) matriz(i - 1) = matriz(i) Next i ReDim Preserve matriz(UBound(matriz) - 1) 

不幸的是没有。 你必须写一个方法来做到这一点。 一个很好的例子是http://www.vbforums.com/showthread.php?562928-Remove-Item-from-an-array

 '~~> Remove an item from an array, then resize the array Public Sub DeleteArrayItem(ItemArray As Variant, ByVal ItemElement As Long) Dim i As Long If Not IsArray(ItemArray) Then Err.Raise 13, , "Type Mismatch" Exit Sub End If If ItemElement < LBound(ItemArray) Or ItemElement > UBound(ItemArray) Then Err.Raise 9, , "Subscript out of Range" Exit Sub End If For i = ItemElement To lTop - 1 ItemArray(i) = ItemArray(i + 1) Next On Error GoTo ErrorHandler: ReDim Preserve ItemArray(LBound(ItemArray) To UBound(ItemArray) - 1) Exit Sub ErrorHandler: '~~> An error will occur if array is fixed Err.Raise Err.Number, , _ "Array not resizable." End Sub 

不是一个答案,而是一个arrays寻址的研究。

这个代码:ReDim保存matriz(1)matriz(1)= 5

用两个元素创build一个数组:0和1 UBound()返回1

以下是一些可能有助于探究问题的代码:

 Option Explicit Sub Macro1() Dim matriz() As Variant Dim x As Variant Dim i As Integer matriz = Array(0) ReDim Preserve matriz(1) matriz(1) = 5 ReDim Preserve matriz(2) matriz(2) = 10 ReDim Preserve matriz(3) matriz(3) = 4 Debug.Print "Initial For Each" For Each x In matriz Debug.Print ":" & x Next x Debug.Print "Initial For i = 0" For i = 0 To UBound(matriz) Debug.Print ":" & matriz(i) Next i Debug.Print "Initial For i = 1" For i = 1 To UBound(matriz) Debug.Print ":" & matriz(i) Next i Debug.Print "remove one" For i = 1 To UBound(matriz) matriz(i - 1) = matriz(i) Next i ReDim Preserve matriz(UBound(matriz) - 1) For Each x In matriz Debug.Print ":" & x Next x Debug.Print "remove one more" For i = 1 To UBound(matriz) matriz(i - 1) = matriz(i) Next i ReDim Preserve matriz(UBound(matriz) - 1) For Each x In matriz Debug.Print ":" & x Next x End Sub 

date:

 Initial For Each :0 :5 :10 :4 Initial For i = 0 :0 :5 :10 :4 Initial For i = 1 :5 :10 :4 remove one :5 :10 :4 remove one more :10 :4