Excel VBA嵌套循环返回运行时错误9

时间:2018-05-30 01:40:42

标签: excel vba excel-vba

在第12次找到循环匹配后,我在rptVals数组上有一个运行时错误9。基本上,rptcount命中247 - 其中rptRows的数量为246.我已经尝试将rptRows的大小加倍和翻两倍,每次我通过第12次比赛时我都会得到错误。我尝试加载一个比第一个工作簿多一行数据的不同数据集,并且在第13次匹配后我得到了错误 - 无论rptRows计数大小如何,但始终匹配报告计数最大计数。

为什么会发生这种情况?另外,我是化学家,而不是程序员,如果这不是最漂亮的代码或最有效的或其他什么,那就很抱歉。如果它有效,我很高兴。另外,我已经了解了字典,但是我对数组和循环的掌握比对字典的掌握要好得多(这显然不是很多,但是很好)。

Sub PrntFllEle()

    With Workbooks("Full Element Analysis Current").Worksheets("All _
    Samples")

    rptRows = Range("H6:IS6").Columns.Count  'here is the start of the 
                                             'problem. rptRows = 246
    'rptrng = rptRows * 2  I made this variable to double/quadruple the _ 
                           size of rptRows count
    rptVals = .Range("H6:IS6" & rptRows).Value

    End With

With Workbooks(FlNm).Worksheets("Report")
    'rEleAn, seen below the range of data captured in a separate sub.
    'This will also have an associated array ElAr from the other sub.

    chkRows = rEleAn.Rows.Count

End With

For rptcount = LBound(rptVals) To UBound(rptVals)
    For chkcount = LBound(ElAr) To UBound(ElAr)

        If rptVals(1, rptcount) <> "" Then    'I had to include this as _   
                                               I have some blank cells _   
                                               in array and this was the _                                               
                                               quickest way to deal with it.
        'This next line is where the run-time error occurs. rptVals = _
         Subscript out of Range and rptcount = 247
        'Note, the UBound(rptVals) is 6241.

            If rptVals(1, rptcount) = Mid((ElAr(chkcount, 1)), 1, 2) Then
                MsgBox rptVals(1, rptcount) 
                'MsgBox just a place holder for now.

            End If
        Else
            Exit For
        End If

    Next
Next

End Sub

所有变量都是全局的,顺便说一下。我检查了这些值,可能影响这一点的一切都是Long。所有数组都是Variants,因为我有字符串和数字要处理。范围适当地暗淡范围。

1 个答案:

答案 0 :(得分:1)

你的......下一个构造默认为你阵列的第一级。你想要第二名。

{{1}}