Excel VBA无法修复运行时错误“9”:下标超出范围

我是excel VBA的新手。 以下是我的代码。 它总是抛出运行时错误。 我试图用我所有的努力来解决这个问题。 谁能拯救我的生命? 我很感激任何回应。

Function GetUniqueAndCount() Dim sheet As Worksheet Set sheet = ActiveSheet Dim index As Integer Dim componentList() As String Dim typeList() As String Dim temp() As String Dim arraySize As Integer Dim row As Integer Dim iVal As Integer Dim horizontal, vertical, borderString As String row = 1 Do Until Application.CountA(sheet.Rows(row)) = 0 temp = Filter(typeList, Cells(row, 3)) On Error GoTo EMPTY_ARRAY: If (UBound(temp) = -1 And Cells(row, 3) <> vbstringnull) Then ReDim Preserve componentList(index) ReDim Preserve typeList(index) componentList(index) = Cells(row, 2) typeList(index) = Cells(row, 3) arraySize = arraySize + 1 index = index + 1 End If EMPTY_ARRAY: Erase temp() row = row + 1 Loop End function 

temp = Filter(typeList, Cells(row, 3))

在第一次迭代中, typeList是未初始化的数组,如果将这样的数组传递给filter()则不返回数组,所以temp保持未初始化,所以UBound(temp)是非法的。

一旦typeList被redimmed你会得到-1如你所料。

在尝试使用它作为filter()的源代码之前testing你已经分配了typeList

也删除On Error并修复造成这种情况的原因,如果不是以上情况。