清除VBA中的空数组 [英] clear empty arrays in VBA

查看:1894
本文介绍了清除VBA中的空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我在VBA中有一个数组,它添加了空字符串元素。



如何删除空数组?



并且数组处于for循环中,我想每次都完全清除数组

我该怎么办?那个?



arr()=没什么不起作用



 对于 i =  1   myfolder.Items.Count 
设置 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 )。值= arr( 1
xlobj.Range( d& i + 1 )。值= arr( 3
xlobj.Range( e& i + 1 )。值= arr( 5
xlobj.Range( f& i + 1 )。值= arr( 7
xlobj.Range( g& i + 1 )。值= arr( 9
xlobj.Range( h& i + 1 )。值= arr( 11

arr()=注意

下一步

解决方案

试试这个:



 擦除 arr 


要从任何数组中删除元素,必须将其余的元素洗牌,然后将整个数组的大小缩小一个。将元素设置为 Nothing 不会这样做,它只是删除元素数据而不影响索引。就个人而言,我不会这样做 - 我会创建一个新的相关项列表,并循环数组,添加我想要保留到列表中的项目。最后,我将使用List< T> .ToArray方法从列表中重新加载数组引用:

  Dim  list 作为 列表(  [ MyClass ])()
对于 每个 m 作为 [ MyClass ] myArray
如果 IWantToKeepThisOne(m)那么
list.Add(m )
结束 如果
下一步
myArray = list.ToArray()


解决方案1(由du [DE])非常好,但需要一些解释。



擦除方法释放内存ory由动态数组使用。 在你的程序再次引用动态数组之前,它必须使用 ReDim 语句重新声明数组变量的'维度

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

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

解决方案

Try this:

Erase arr


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:

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()


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.


这篇关于清除VBA中的空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆