简体   繁体   English

VBA阵列-下标超出范围

[英]VBA Array - subscript out of range

I'm hoping to create a VBA array with 5 rows and 2 columns 我希望创建一个5行2列的VBA数组

varData = [{0, 0; 0, 0; 0, 0; 0, 0; 0, 0}]

and change the values according to a case 并根据情况更改值

select Case sth
                Case "1"
                    varData(0, 0) = varData(0, 0) + Cells(I, 1).Value
                Case "2"
                    varData(0, 1) = varData(0, 1) + Cells(I, 1).Value
                Case "3"
                    varData(0, 2) = varData(0, 2) + Cells(I, 1).Value
                Case "4"
                    varData(0, 3) = varData(0, 3) + Cells(I, 1).Value
                Case "5"
                    varData(0, 4) = varData(0, 4) + Cells(I, 1).Value
                Case Else
                    '?
            End Select

I'm getting an error on this line: 我在这条线上出现错误:

varData(0, 2) = varData(0, 2) + Cells(I, 1).Value

saying "subscript out of range" 说“下标超出范围”

I also tried changing the array to 我也尝试将数组更改为

varData = [{0, 0, 0, 0, 0; 0, 0, 0, 0, 0}]

Please help me understand how I'm out of range 请帮助我了解我如何超出范围

You are using a shorthand of Evaluate and as such you are loading the array through the same mechanism as the sheet and as such the base is 1 not 0. 您使用的是Evaluate的简写,因此通过与工作表相同的机制加载数组,因此基数为1而不是0。

在此处输入图片说明

So you want to change the references as such: 因此,您想这样更改引用:

       select Case sth
            Case "1"
                varData(1, 1) = varData(0, 0) + Cells(I, 1).Value
            Case "2"
                varData(1, 2) = varData(0, 1) + Cells(I, 1).Value
            Case "3"
                varData(1, 3) = varData(0, 2) + Cells(I, 1).Value
            Case "4"
                varData(1, 4) = varData(0, 3) + Cells(I, 1).Value
            Case "5"
                varData(1, 5) = varData(0, 4) + Cells(I, 1).Value
            Case Else
                '?
        End Select

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

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