What is the code to reset an array to its default state so that all the elements are erased?
Asked
Active
Viewed 8,757 times
0
-
1I'm no VB expert so won't attempt any sample code, but [Array.Clear](http://msdn.microsoft.com/en-us/library/system.array.clear(v=vs.100).aspx) comes to mind as a starting point. – Joachim Isaksson Feb 08 '14 at 07:25
-
possible duplicate of [vba: clear entire array](http://stackoverflow.com/questions/3018510/vba-clear-entire-array) – aksu Feb 08 '14 at 07:32
-
Possible duplicate of [What is the best way to clear an array of strings?](http://stackoverflow.com/questions/713867/what-is-the-best-way-to-clear-an-array-of-strings) – Mark Hurd Aug 10 '16 at 11:38
3 Answers
3
you can try Array.Clear method :
Array.Clear(myArray, 0, myArray.Length)
that will revert value of each array element to default (0
, false
, or Nothing
depending on the element type as described in the link above).
Another option is to use Erase
Erase myArray
that will turn myArray
variable to Nothing
.

har07
- 88,338
- 12
- 84
- 137
-
thanks, I use erase but when I do, and I try to reuse the array, I get value cannot be null error – Marcel Feb 08 '14 at 08:55
-
yep as pointed above, it turns to `Nothing`. So you need to reinitialize the array before assigning new value to the array element. If you don't want to reinit, go with `Array.Clear` option. – har07 Feb 08 '14 at 08:58
-
where i put myArray.Length, what if the array has no bounds such as Names() – Marcel Feb 08 '14 at 09:02
-
hmm.. I'm not sure I get the question, if your array is `Names()` then you can do `Array.Clear(Names, 0, Names.Length)`. `Length` is a built in property of array that indicates it's size/length – har07 Feb 08 '14 at 09:05
-
1oh ok I thought you had to declare the size of the array there. All fixed, thanks for the answer – Marcel Feb 08 '14 at 09:06