如何清除整个阵列?

时间:2010-06-10 21:04:52

标签: arrays excel vba

我有一个这样的数组:

Dim aFirstArray() As Variant

如何清除整个阵列? 收藏怎么样?

8 个答案:

答案 0 :(得分:104)

您可以使用EraseReDim语句清除数组:

Dim threeDimArray(9, 9, 9), twoDimArray(9, 9) As Integer
Erase threeDimArray, twoDimArray
ReDim threeDimArray(4, 4, 9)

<强> See the different usage of each method here.

<强>更新

要删除集合,请迭代其项目并使用remove方法:

For i = 1 to MyCollection.Count
  MyCollection.Remove 1 ' Remove first item
Next i

答案 1 :(得分:19)

要在VBA中删除动态数组,请使用指令Erase

示例:

Dim ArrayDin() As Integer    
ReDim ArrayDin(10)    'Dynamic allocation 
Erase ArrayDin        'Erasing the Array   

希望这有帮助!

答案 2 :(得分:6)

这很简单:

Erase aFirstArray

答案 3 :(得分:2)

[your Array name] = Empty

然后数组将没有内容,可以再次填充。

答案 4 :(得分:1)

ReDim aFirstArray(0)

这会将数组的大小调整为零并清除所有数据。

答案 5 :(得分:0)

我遇到了使用dim / redim清除整个阵列失败的情况:

有2个模块范围的数组,在用户表单中是Private,

一个数组是动态的,使用类模块,另一个是固定的,有一个特殊的类型。

Option Explicit

Private Type Perso_Type
   Nom As String
   PV As Single 'Long 'max 1
   Mana As Single 'Long
   Classe1 As String
   XP1 As Single
   Classe2 As String
   XP2 As Single
   Classe3 As String
   XP3 As Single
   Classe4 As String
   XP4 As Single
   Buff(1 To 10) As IPicture 'Disp
   BuffType(1 To 10) As String
   Dances(1 To 10) As IPicture 'Disp
   DancesType(1 To 10) As String
End Type

Private Data_Perso(1 To 9, 1 To 8) As Perso_Type

Dim ImgArray() As New ClsImage 'ClsImage is a Class module

我有一个声明为public的子,用于清除这些数组(以及相关的运行时创建的控件),如下所示:

Public Sub EraseControlsCreatedAtRunTime()
Dim i As Long
On Error Resume Next
With Me.Controls 'removing all on run-time created controls of the Userform :
    For i = .Count - 1 To 0 Step -1 
        .Remove i
    Next i
End With
Err.Clear: On Error GoTo 0

Erase ImgArray, Data_Perso
'ReDim ImgArray() As ClsImage ' i tried this, no error but wouldn't work correctly
'ReDim Data_Perso(1 To 9, 1 To 8) As Perso_Type 'without the erase not working, with erase this line is not needed.
End Sub

注意:最后一个子句首先使用Call FormName.SubName从外部(其他表单和类模块)调用,但必须将其替换为Application.Run FormName.SubName,减少错误,不要问为什么..

答案 6 :(得分:0)

为自己找一个更好的用法: 我通常会测试变量是否为空,并且所有上述方法都会因测试而失败。我发现你实际上可以将变量设置为空:

Dim aTable As Variant
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
If IsEmpty(aTable) Then
    'This is False
End If
ReDim aTable(2)
aTable = Empty
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
Erase aTable
If IsEmpty(aTable) Then
    'This is False
End If

这样我得到了我想要的行为

答案 7 :(得分:-1)

仅使用$-声明

Redim