0

I'm hoping to create a VBA array with 5 rows and 2 columns

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

4
  • What's in I when it fails? Commented Jul 22, 2019 at 20:07
  • What if you write a line of code that prints varData(0,2) ? Does that fail? Commented Jul 22, 2019 at 20:09
  • @nicomp I = 12, the first relevant line of data. When removed, the line with varData(0, 0) is the one with the error Commented Jul 22, 2019 at 20:15
  • @nicomp MsgBox (varData(0, 0)) produces the same error: subscript out of range Commented Jul 22, 2019 at 20:17

1 Answer 1

3

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.

enter image description here

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.