有没有办法删除数组的第一个元素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
这是在回避错误: 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