简体   繁体   中英

Excel VBA Cannot fix the Runtime error ' 9': Subscript out of range

I am a newbie of excel VBA. Below is my code. It always throw runtime error. I have tried to fix it with my all effort. Can anyone save my life? I appreciate any response.

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 is an uninitialized array in the first iteration, if you pass such an array to filter() no array is returned so temp remains uninitialized so UBound(temp) is illegal.

Once typeList has been redimmed you would get back -1 as you expect.

Test that you have assigned to typeList before attempting to use it as a source for filter()

Also remove the On Error and fix whatever causes that condition if its not the above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM