【问题标题】:Subscript error when trying to remove blank values from an array in VBA尝试从 VBA 中的数组中删除空白值时出现下标错误
【发布时间】: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


    【解决方案1】:

    范围是多维数组..(即 MyArray(#,#) 其中第一个索引是行,第二个是列。

    改变

     If MyArr(i) <> "" Then 
    

     If MyArr(i,1) <> "" Then 
    

    如果您的范围只有一列,则第二个索引将始终为 1

    【讨论】:

    • 试试这个 ReDim NewArr(UBound(MyArr), 1) Ubound 将是第一个数组中的行数。
    • 另外,您必须在将值分配给新数组后增加 J 的值(因此将其分配给索引 0...
    • 好消息是我不再收到错误消息(谢谢!)。坏消息是我的数组中仍然有空白条目(如即时窗口所示)。以下是对代码的修改:J = LBound(MyArr) - 1 For i = LBound(MyArr) To UBound(MyArr) If MyArr(i, 1) &lt;&gt; "" Then J = J + 1 NewArr(J, 1) = MyArr(i, 1) End If Next i ReDim Preserve NewArr(LBound(MyArr) To UBound(MyArr), 1)
    • 好吧,您将数组重新调整为与第一个数组相同的大小,这意味着(可能)至少最后一行将为空。一种选择是将数组分配给一个范围对其进行排序并将范围分配给一个数组(跟踪您写入了多少值以了解新数组的大小)。
    • 谢谢。我曾考虑过这一点,但目标是将数组保留在代码中。
    猜你喜欢
    • 2020-03-06
    • 1970-01-01
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多