3

This is an awesomely simple problem, but I've been breaking my head against it for an hour. I'm trying to do the following:

  1. define a VBA array from a named range in my spreadsheet
  2. Access an item in that array

Now, if the named range happens to cover a multi-dimensional area (rows and columns), then this works fine:

foobar = Range("two_dimensional_range")
MsgBox foobar(1,1)

However, if the named range consists of a single dimension (just a column) of data, then this produces a "Subscript Out of Range" error:

foobar = Range("one_dimensional_range")
MsgBox foobar(1)

I've verified that foobar is really an array. I can iterate through it with For Each ... Next. If I call Ubound(foobar) then it gives me the correct size. I just can't access a single element of it directly!

What am I doing wrong?

0

1 Answer 1

6

When you assign a range (Not a single cell) to a variant array, It will always be a multidimensional array so this MsgBox foobar(1,1) will still work in the 2nd instance.

See this example

Option Explicit

Sub Sample()
    Dim Ar As Variant

    Ar = Range("A1:A2")

    Debug.Print Ar(1, 1)
    Debug.Print Ar(2, 1)
End Sub

Another example

Option Explicit

Sub Sample()
    Dim Ar As Variant

    Ar = Range("A1:B2")

    '~~> Get Values from Col A
    Debug.Print Ar(1, 1)
    Debug.Print Ar(2, 1)

    '~~> Get Values from Col B
    Debug.Print Ar(1, 2)
    Debug.Print Ar(2, 2)
End Sub
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.