【发布时间】:2014-09-24 20:55:35
【问题描述】:
我正在尝试从 Excel 数据表中名为 TY[L3 Name](1 列,X 行长)的字段加载的数组中删除空白条目。下面的代码旨在从数组中删除所有空白值(一旦加载了范围),并返回一个新数组,其中的行中只有数据。我稍后会想将此数组传递到一个集合中以删除重复项,但我想弄清楚为什么我不能先摆脱空白(现在我正处于我只想了解如何做到这一点无论我是否将其传递给其他东西)。
代码在 ReDim Preserve 行出错。我首先将 NewArr 调整为 MyArr 表,但最后返回了空白行。然后我尝试调整它的大小,因此我只有包含数据的行,但我似乎无法让 NewArr() 数组在没有错误的情况下执行此操作。
我正在使用即时窗口来验证没有空白条目(目前 TY[L3 Name] 范围末尾有 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
【问题讨论】:
标签: arrays excel vba for-loop subscript