Как очистить массив vba excel

Return to VBA Code Examples

In this Article

  • Clear Entire Array
  • Resize and Clear Array
    • Clear Part of an Array
    • Loop Through Entire Array – Resetting Values

This tutorial will teach you how to clear an Array in VBA.

Clear Entire Array

To clear an entire array, you can use the Erase Statement:

Erase arrExample

In practice:

Sub ClearArray()
    'Create Static Array
    Dim arrExample(1 to 3) as String
 
    'Define Array Values
    arrExample(1) = "Shelly"
    arrExample(2) = "Steve"
    arrExample(3) = "Neema"
 
    'Erase Entire Array
    Erase arrExample

    'Check Array Value
    MsgBox arrExample(1)
End Sub

Resize and Clear Array

If your Array is dynamic (A dynamic array is an array that can be resized, as opposed to a static array which can not be resized), you can use the ReDim Command to resize the array, clearing the entire array of values.

'Erase Entire Array
ReDim arrExample(1 To 4)

Full Example:

Sub ClearArray2()
    'Create Dynamic Array
    Dim arrExample() As String
    ReDim arrExample(1 To 3)
 
    'Define Array Values
    arrExample(1) = "Shelly"
    arrExample(2) = "Steve"
    arrExample(3) = "Neema"
 
    'Erase Entire Array
    ReDim arrExample(1 To 4)
    
    'Check Array Value
    MsgBox arrExample(1)
End Sub

Clear Part of an Array

As mentioned above, the ReDim Command will resize an array, clearing all values from the array.  Instead you can use ReDim Preserve to resize the array, preserving any existing values. In practice, this can be used to quickly clear part of an array.

'Erase Position 3+
ReDim Preserve arrExample(1 To 2)

Full Example:

Sub ClearArray3()
    'Create Dynamic Array
    Dim arrExample() As String
    ReDim arrExample(1 To 3)
 
    'Define Array Values
    arrExample(1) = "Shelly"
    arrExample(2) = "Steve"
    arrExample(3) = "Neema"
 
    'Erase Position 3+
    ReDim Preserve arrExample(1 To 2)
    
    'Resize to 3 Positions
    ReDim Preserve arrExample(1 To 3)
    
    'Check Array Value
    MsgBox arrExample(3)
End Sub

Loop Through Entire Array – Resetting Values

Instead of clearing array values using Erase or ReDim, you could loop through the entire array, resetting each value.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

i fell into a case where clearing the entire array failed with dim/redim :

having 2 module-wide arrays, Private inside a userform,

One array is dynamic and uses a class module, the other is fixed and has a special type.

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

And i have a sub declared as public to clear those arrays (and associated run-time created controls) from inside and outside the userform like this :

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

note : this last sub was first called from outside (other form and class module) with Call FormName.SubName but had to replace it with Application.Run FormName.SubName , less errors, don’t ask why…

Home / VBA / Arrays / VBA Clear Array (Erase)

You need to use the “Erase” statement to clear an array in VBA. Add the keyword “Erase” before the name of the array that you want to clear but note that all the values will be reset from the array. In the following array, you have 3 elements and we have used the erase statement to erase all.

Sub myMacro1()

Dim myArray() As Long
ReDim myArray(4)

myArray(1) = 1
myArray(2) = 2
myArray(3) = 3
myArray(4) = 4

ReDim myArray(1 To 5)

MsgBox myArray(3)

End Sub

And with that statement, it has erased all the elements from the array, and when we use the Debug.Print (Immediate Window) to get the array element, there’s nothing left.

Clear Dynamic Array

When you use ReDim it removes all the elements. But you can use the preserve statement to preserve some of the elements and clear an array partially. In the following example, we have an array and we have partially erased the fourth value and then re-defined the elements to 5.

And if you want to clear a dynamic array partially.

Sub myMacro2()

Dim myArray() As Long
ReDim myArray(1 To 4)

myArray(1) = 1
myArray(2) = 2
myArray(3) = 3
myArray(4) = 4

'erase position 4 but preserve the 1,2, and 3
ReDim Preserve myArray(1 To 3)

'redefine the array items to five
ReDim Preserve myArray(1 To 5)

MsgBox myArray(3)

End Sub

Important Points

  1. When you erase a fixed array:
    1. In an array that has all the values of a string, erase statement will reset all the elements to (variable length) to the zero-length string “” and (fixed length) to zero.
    2. In an array which has numeric values, erase statement will reset all the elements to zeros.
    3. In an array which as variant data type, erase statements will reset all the elements to empty.
    4. In an array which has objects, erase statement will reset all the elements to nothing.
    5. In an array which has objects, erase statement will reset all the elements if it were a separate variable.
  2.   When you erase a dynamic array erase statement frees the space used by the dynamic array.

I’m working on an Excel VBA addin that exchanges objects with a COM server, something like this:

'get an array of objects
Dim Ents() As ISomething
ComObject.GetEntities Ents

'send an array with 10 objects
ReDim Ents(9)
Set Ents(0) = ...
...
ComObject.SetEntities Ents

Getting the arrays works well: if the array contains objects it works as expected, if the array is empty then UBound(Ents) = -1 and everything works as expected.

Sending the arrays works only with not empty arrays, because I can’t Redim Ents(-1), and Eraseing the array both VBA and the COM server crash: Debug.Print UBound(Ents) crashes in VBA and who knows what crashes the server.

It looks like the Erase statement leaves the array undefined/corrupted rather than empty.

EDIT (clarification to a comment below):

Executing this code it crashes because it can’t calculate the UBound:

Sub Test()
  Dim Ents() As ISmartId
  Debug.Print UBound(Ents)
End Sub

But if you add Ents to the watch window, then set a break point to the Debug.Print line and execute, the debugger shows the ISmartId(0 to -1) in the Type column. After this the execution continues without crash, and the Debug window shows the expected -1.

It looks like the debugger was able to correctly initialize the empty array the way I need it just to show its value.

i упал в случай, когда очистка всего массива завершилась неудачей с помощью 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

И у меня есть sub, объявленный как 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

note: последний последний был вызван извне (другой модуль формы и класса) с Call FormName.SubName, но ему пришлось заменить его на Application.Run FormName.SubName, меньше ошибок, не спрашивайте, почему…

Понравилась статья? Поделить с друзьями:
  • Как очистить лишние пробелы в excel
  • Как очистить лист в excel от формул
  • Как очистить кэш файла excel
  • Как очистить кэш сводных таблиц в excel
  • Как очистить всю страницу excel