繁体   English   中英

将值分配给数组时,Excel VBA下标超出范围错误

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

我正在研究一个类似的数据集,如下所示:

我的数据详情

我正在按照列作业循环输入数据,并试图找出为该作业映射的继任者。 我正在将继任者退休年份分配给我的二维数组的帖子。 发布此我正在尝试将数组分配给列表框。 这是我的代码:

    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

当第二个 for 循环第二次运行时,我不断收到下标超出范围错误。 任何帮助将不胜感激,非常感谢。

我正在使用 countrow 向数组添加值,但 countrow 将具有更大的值。 我又用了一个柜台绕过它。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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