简体   繁体   中英

Excel VBA Subscript out of range error in array when assigning values to array

I am working on a similar data set as below:

My data details

I am looping in the data as per Column Job and trying to find out successor mapped for the job. Post which I am assigning the Successor and Retirement year to my 2 dimensional array. Post this I am trying to assign the array to a listbox. Here is my code:

    Dim hjselected As Variant
    hjselected = frmform1.ComboBox1.Value

    iRow = [Counta(Database_HJ!A:A)] - 1
    Dim arrayrow As Variant 
    arrayrow = 0 'variable for array row size
    For countRow = 2 To iRow 'to find array row size I need based on number of incumbent
            If (hjselected = Sheet2.Cells(countRow, 1)) Then
                   arrayrow = arrayrow + 1
            End If
    Next countRow
    Dim varA() As Variant
    ReDim varA(arrayrow, 6)
    For countRow = 2 To iRow
            If (hjselected = Sheet2.Cells(countRow, 1)) Then
                   varA(countRow, 1) = Sheet2.Cells(countRow, 9)
                   varA(countRow, 2) = Sheet2.Cells(countRow, 10)
                   varA(countRow, 3) = Sheet2.Cells(countRow, 11)
                   varA(countRow, 4) = Sheet2.Cells(countRow, 12)
                   varA(countRow, 5) = Sheet2.Cells(countRow, 13)
                   varA(countRow, 6) = Sheet2.Cells(countRow, 14)
            End If
    Next countRow
    frmform1.ListBox1.List = varA

I am constantly getting a Subscript out of range error when the second for loop is running for the 2nd time. Any help would be appreciated, thank you very much.

I was using the countrow to add values to the array but countrow will have much larger value. I used one more counter to go around it.

Dim arrayI As Long
arrayI = 1
For countRow = 2 To iRow
        If (hjselected = Sheet2.Cells(countRow, 1)) Then
                    varA(arrayI, 1) = Sheet2.Cells(countRow, 9)
                    varA(arrayI, 2) = Sheet2.Cells(countRow, 10)
                    varA(arrayI, 3) = Sheet2.Cells(countRow, 11)
                    varA(arrayI, 4) = Sheet2.Cells(countRow, 12)
                    varA(arrayI, 5) = Sheet2.Cells(countRow, 13)
                    varA(arrayI, 6) = Sheet2.Cells(countRow, 14)
                    arrayI = arrayI + 1
        End If
Next countRow

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