简体   繁体   English

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

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

my code copies all the values of a table in excel on an array an filter them and fill a combobox with it, but I keep geting this error on my code and after debuging it's seems that the error is due to Redim Preserve ... can you check it please ? 我的代码将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

There is nothing to "Preserve" when the Redim statement is called for the first time in your loop. 当您的循环中第一次调用Redim语句时,没有任何内容可以“保留”。 Call Redim without "Preserve" when you dimension the array for the first time. 首次为阵列标注尺寸时,调用不带“保留”功能的Redim。

If the line of code that dimensions variables is real code it is surprising that it doesn't call an error. 如果确定变量尺寸的代码行是真实代码,那么它没有调用错误就令人惊讶。 I suggest to place each Dim statement in a line by itself, for better readability of the code if for no other reason, and avoid the use of the colon quite generally but especially for the purpose of mixing declarations with value assignment. 我建议将每个Dim语句单独放在一行中,以提高代码的可读性(如果没有其他原因),并避免在一般情况下使用冒号,特别是为了将声明与值分配混合使用。

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

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