【发布时间】:2014-08-01 21:27:13
【问题描述】:
我正在尝试运行一个简单公式以从数组中删除空白条目。我正在使用的数组是从我在 Excel 中设置的名为 TY 的数据表中的字段加载的。该字段的名称是 TY[L3 Number]。我想保持这个数组动态,因为它可能会随着用户从数据表中添加或删除行而改变。我使用的测试数据有 218 行,其中 210 行有重复的条目(稍后我将要删除),以及 8 个“”条目。
运行宏时,我在 if 语句的第一行收到运行时错误 9“下标超出范围”。
我确实花了几个小时试图理解为什么 VBA 给我这个错误。我的理解是,这是由于数组的大小不正确,无法处理传递给它的数据。我已经使用调试窗口来验证两个数组的大小是否正确。
我对编程很陌生,并且在学习过程中自学,但我只是自己找到解决方案。
Sub BuildArray()
' Load array
Dim MyArr()
Dim J As Long
' Size array
MyArr() = Range("TY[L3 Number]")
ReDim NewArr(LBound(MyArr) To UBound(MyArr))
' 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
J = LBound(MyArr) - 1 ' Added this recently while testing the theory that J may start at the 2nd index in the loop, did not help
For i = LBound(MyArr) To UBound(MyArr)
If MyArr(i) <> "" Then ' This is where I error out
J = J + 1
NewArr(J) = MyArr(i)
End If
Next i
ReDim Preserve NewArr(LBound(MyArr) To J)
' Debug Window to show results of revised array.
Dim c As Long
For c = LBound(NewArr) To UBound(NewArr)
Debug.Print NewArr(c)
Next
Debug.Print "End of List"
End Sub
【问题讨论】:
标签: arrays excel subscript vba