删除VBA数组的第一个元素

Nun*_*ira 10 arrays excel vba excel-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
Run Code Online (Sandbox Code Playgroud)

这是在回避错误: Subscript out of range

Man*_*ian 13

在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)
Run Code Online (Sandbox Code Playgroud)

  • 虽然这是一个很好的答案,我正在这样做,但你可能会注意到,如果目标是拥有类似队列的东西,那么这将是一种非常低效的实现方式.可能会修改大量使用此类内容的代码,以免需要它. (5认同)

小智 5

遗憾的是没有.你必须写一个方法来做到这一点.一个很好的例子是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
Run Code Online (Sandbox Code Playgroud)