Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I have an array in VBA, which adds empty string elements.

How can I delete the empty arrays?

And the Array is in a for-loop and I want to clear the array fully every time
How can I do that?

the "arr() = nothing" doesn't work

VB
For i = 1 To myfolder.Items.Count
  Set myItem = myfolder.Items(i)
  arr = Split(myItem.Body, vbCrLf)
  

  
  xlobj.Range("a" & i + 1).Value = myItem.SenderName
  xlobj.Range("b" & i + 1).Value = myItem.ReceivedTime
  xlobj.Range("c" & i + 1).Value = arr(1)
  xlobj.Range("d" & i + 1).Value = arr(3)
  xlobj.Range("e" & i + 1).Value = arr(5)
  xlobj.Range("f" & i + 1).Value = arr(7)
  xlobj.Range("g" & i + 1).Value = arr(9)
  xlobj.Range("h" & i + 1).Value = arr(11)
  
  arr() = noting

 Next
Posted

Try this:

VB
Erase arr
 
Share this answer
 
Comments
Maciej Los 28-Mar-13 4:48am    
Good answer!
+5
Leo Chapiro 28-Mar-13 4:56am    
Thank you, Maciej ! :)
To remove an element from any array, you have to "shuffle" the remaining elements out, and then shrink the size of the whole array by one. Setting an element to Nothing does not do that, it just removes the element data without affecting the indexes. Personally, I wouldn't do it - I would create a new List of the relevant items, and loop though the array, adding items that I want to keep to the list. Then finally I would reload the array reference from the list with the List<T>.ToArray method:
VB
Dim list As New List(Of [MyClass])()
For Each m As [MyClass] In myArray
    If IWantToKeepThisOne(m) Then
        list.Add(m)
    End If
Next
myArray = list.ToArray()
 
Share this answer
 
Comments
Maciej Los 28-Mar-13 4:42am    
OriginalGriff,
VBA doesn't support List(Of T)
Solution 1 (by du[DE]) is very good, but need some explanation.

Erase method frees the memory used by dynamic arrays. Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement.
 
Share this answer
 
Comments
chenduran10 28-Mar-13 5:12am    
Why I can't do the ReDim statement in this code?
Maciej Los 28-Mar-13 5:18am    
Can't you? You can!
In your code you don't need to re-declare a size of array, because Split() function[^] do it in each step of for-next loop.
You should erase array outside of loop.
Leo Chapiro 28-Mar-13 5:12am    
Another +5 for Maciej for this really good explanation! :)
Maciej Los 28-Mar-13 5:18am    
Thank you ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900