2010-06-10 259 views

回答

82

您可以使用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 
+0

怎麼樣的集合? – 2010-06-10 21:10:21

+0

@I:請看我更新的答案。 – Sarfraz 2010-06-10 21:13:12

+0

只是簡單的說明,至少對於VBA來說,你不能ReDim用維度聲明的數組。 – KevenDenen 2010-06-11 03:49:16

15

要在VBA中刪除動態數組,請使用指令Erase

例子:

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

希望這有助於!

+3

問題提出後兩年發佈答案的原因是什麼,前提是這個答案已經發布了? – GSerg 2012-03-22 15:04:35

+0

@GSerg這是一個非常好的句子。 – 2012-03-22 16:33:21

+7

對你們倆都是無價的評論。沒有答案顯示擦除。此外,Andres公佈了他的答案差不多一年之後,它實際上給了我一直在尋找的單線代碼解決方案。如果我可以對你的兩個評論下決心,我會的。 – oscilatingcretin 2013-02-13 13:51:01

7

它很簡單,只要:

Erase aFirstArray 
+0

與4年前發佈的Andres相同的答案。看不到這是如何有用。 – trincot 2017-11-14 14:16:19

0

我陷入其中清除整個陣列失敗,暗淡/ 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,錯誤更少,代替它不要問爲什麼......

2
[your Array name] = Empty 

則數組將沒有內容並且可以再次填充。

+1

這不起作用。您會收到「編譯錯誤:無法分配給數組」 – seadoggie01 2017-11-20 15:21:34

0

僅使用Redim聲明

Dim aFirstArray() As Variant 

Redim aFirstArray(nRows,nColumns) 
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 

這樣我得到的行爲我想