【发布时间】:2011-03-02 09:40:09
【问题描述】:
我有一个这样的数组:
Dim aFirstArray() As Variant
如何清除整个数组? 集合呢?
【问题讨论】:
我有一个这样的数组:
Dim aFirstArray() As Variant
如何清除整个数组? 集合呢?
【问题讨论】:
您可以使用Erase 或ReDim 语句来清除数组。每个示例都显示在the MSDN documentation 中。例如:
Dim threeDimArray(9, 9, 9), twoDimArray(9, 9) As Integer
Erase threeDimArray, twoDimArray
ReDim threeDimArray(4, 4, 9)
要删除一个集合,您需要遍历它的项目并使用Remove 方法:
For i = 1 to MyCollection.Count
MyCollection.Remove 1 ' Remove first item
Next i
【讨论】:
ReDim会怎样?它是简单地将值重置为零还是分配一个新数组?我担心的是调用ReDim 在循环中重置大数组时的时间性能
要在 VBA 中删除动态数组,请使用指令 Erase。
例子:
Dim ArrayDin() As Integer
ReDim ArrayDin(10) 'Dynamic allocation
Erase ArrayDin 'Erasing the Array
希望对您有所帮助!
【讨论】:
就这么简单:
Erase aFirstArray
【讨论】:
为自己找到更好的用途: 我通常测试一个变体是否为空,并且上述所有方法都失败了。我发现您实际上可以将变体设置为空:
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
这样我得到了我想要的行为
【讨论】:
[your Array name] = Empty
那么数组就没有内容了,可以再次填充。
【讨论】:
ReDim aFirstArray(0)
这会将数组的大小调整为零并擦除所有数据。
【讨论】:
我遇到了一个用 dim/redim 清除整个数组失败的情况:
有 2 个模块范围的数组,在一个用户表单中是私有的,
一个数组是动态的并使用类模块,另一个是固定的并具有特殊类型。
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 替换它,错误更少,不要问为什么......
【讨论】:
只使用Redim 声明
Dim aFirstArray() As Variant
Redim aFirstArray(nRows,nColumns)
【讨论】: