我正在尝试从excel中的数据表中从名为TY [L3 Name](1列,X行长)的字段加载的数组中删除空白条目。下面的代码旨在从数组中删除所有空值(一旦加载了范围),并返回一个新数组,其中的行只包含数据。我想稍后将这个数组传递给一个集合以删除重复项,但我想弄清楚为什么我不能首先获得空白(现在我正处于我想要了解如何无论我是否将其传递给其他内容,都要这样做。
ReDim Preserve行的代码错误。我首先将NewArr调整为MyArr表,但最后返回了空白行。然后我尝试调整它的大小,所以我只有包含数据的行,但我似乎无法让NewArr()数组在没有错误的情况下执行此操作。
我正在使用即时窗口来验证没有空白条目(目前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
答案 0 :(得分:3)
在VBA中处理数组可能会非常棘手,但我认为下面的示例将向您展示如何使用不同的策略来填充&#34; No Blanks&#34; Array
可能有效:
假设我们从一个Worksheet
开始,CoolRange
的名称如下所示:
生成没有空格的数组可以这样做:
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
总而言之,我们:
从您的问题描述中,听起来您最终会使用Collection
删除重复项 - 喜欢它。出于好奇,你将使用非空白但重复的数组?