繁体   English   中英

运行时错误9“下标超出范围”数组redim保存vba

[英]Runtime error 9 “subscript out of range” array redim preserve vba

我的代码将excel中表的所有值复制到数组上,对其进行过滤,并用它填充组合框,但是我不断在我的代码上收到此错误,并且在调试后,看来该错误是由于Redim Preserve引起的...可以你检查一下吗?

' FIll CB2()

 Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets("D1") 
 Dim LC As Long 
 Dim i As Long 
 Dim PN As Long 
 Dim myArray() As String 
 Dim j As Long 
 Dim k As Long 
 Dim temp As String

LC = ws.Cells(ws.Rows.Count, 4).End(xlUp).Row

    For i = 1 To LC

        If StrComp(CB1.List(CB1.ListIndex, 0), ws.Cells(i, 4), vbTextCompare) = 0 Then



        'Set you array with the right dimension
        ReDim Preserve myArray(0 To PN, 0 To 1)

        myArray(PN, 0) = ws.Cells(i, 2)
        myArray(PN, 1) = ws.Cells(i, 3)

        PN = PN + 1


        End If

    Next i 
End Sub

当您的循环中第一次调用Redim语句时,没有任何内容可以“保留”。 首次为阵列标注尺寸时,调用不带“保留”功能的Redim。

如果确定变量尺寸的代码行是真实代码,那么它没有调用错误就令人惊讶。 我建议将每个Dim语句单独放在一行中,以提高代码的可读性(如果没有其他原因),并避免在一般情况下使用冒号,特别是为了将声明与值分配混合使用。

暂无
暂无

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

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