从由范围加载的数组中删除空白条目

我试图删除一个数组,从一个名为TY [L3名称](1列,X行长)从Excel中的数据表加载的空白条目。 下面的代码旨在从数组中删除所有空值(一旦它已经被加载范围),并返回一个新的数组,其中只有数据的行。 我想将这个数组传递给一个集合,以删除重复,但我想弄清楚为什么我不能先乘坐空白(现在我在一个点,我只是想了解如何做到这一点不pipe我是否通过这个别的东西或不)。

ReDim Preserve行代码错误。 我首先将NewArr的大小设置为MyArr表,但最后返回空行。 然后我试图调整它,所以我只有行中的数据,但我似乎无法得到的NewArr()数组做这个没有错误。

我正在使用立即窗口来validation没有空白条目(目前在TY [L3名称]范围的末尾有8行)。

Sub BuildArray() ' Load array Dim MyArr() Dim j As Long ' Size array MyArr() = Range("TY[L3 Number]") ReDim NewArr(LBound(MyArr) To UBound(MyArr), 1) ' For Loop to search for Blanks and remove from Array ' The Lbound and UBound parameters will be defined by the size of the TY[L3 Number] field in the TY Table For i = LBound(MyArr) To UBound(MyArr) If MyArr(i, 1) <> "" Then j = j + 1 NewArr(j, 1) = MyArr(i, 1) End If Next i ReDim Preserve NewArr(1 To j, 1) 'Error out here; "Subscript out of range." Can't seem to get this Array to new size without blank entries. ' Debug Window to show results of revised array. Dim c As Long For c = LBound(NewArr) To UBound(NewArr) Debug.Print NewArr(c, 1) Next Debug.Print "End of List" End Sub 

在VBA中处理数组可能会非常棘手,但我认为下面的示例将向您展示如何填充“No Blanks” Array的不同策略:

假设我们从一个WorksheetCoolRange命名如下所示:

开始

生成一个没有空白的数组可以这样做:

 Option Explicit Sub BuildArrayWithoutBlanks() Dim AryFromRange() As Variant, AryNoBlanks() As Variant Dim Counter As Long, NoBlankSize As Long 'set references and initialize up-front ReDim AryNoBlanks(0 To 0) NoBlankSize = 0 'load the range into array AryFromRange = ThisWorkbook.Names("CoolRange").RefersToRange 'loop through the array from the range, adding 'to the no-blank array as we go For Counter = LBound(AryFromRange) To UBound(AryFromRange) If AryFromRange(Counter, 1) <> "" Then NoBlankSize = NoBlankSize + 1 AryNoBlanks(UBound(AryNoBlanks)) = AryFromRange(Counter, 1) ReDim Preserve AryNoBlanks(0 To UBound(AryNoBlanks) + 1) End If Next Counter 'remove that pesky empty array field at the end If UBound(AryNoBlanks) > 0 Then ReDim Preserve AryNoBlanks(0 To UBound(AryNoBlanks) - 1) End If 'debug for reference For Counter = LBound(AryNoBlanks) To UBound(AryNoBlanks) Debug.Print (AryNoBlanks(Counter)) Next Counter Debug.Print "End of List" End Sub 

所以,总结一下,我们:

  1. 为我们的最终arrays创build一个一维数组,删除空白
  2. 迭代原始数组(带有空格)
  3. 除非数组字段为空,否则我们增加非空的计数器,然后将该值添加到非空数组中,然后展开非空数组
  4. 吹走我们的非空数组中最后讨厌的空字段

从你的问题描述来看,这听起来像你最终将剥离重复与Collection – 爱它。 出于好奇,你会用什么非空白但重复数组?