我正在尝试运行一个简单的公式来从数组中删除空白条目。我正在使用的数组从数据表中的字段加载,我在Excel中设置为Ty。此字段的名称是TY [L3号码]。我想保持这个数组动态,因为它可能会随着用户添加或从数据表中删除行而改变。我使用的测试数据有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
.

有帮助吗?

解决方案

范围是多维数组。(即myArray(#,#) 第一个索引将是行和第二列的地方。

更改

 If MyArr(i) <> "" Then 
.

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top