Passing a Excel table to array in VBA

rkaczano

Board Regular
Joined
Jul 24, 2013
Messages
141
Office Version
  1. 365
Platform
  1. Windows
I have a routine that loads data into a array as follows:

Dim locations() As Variant
locations = Array(Array("San Francisco", 37.7749, -122.4194), _
Array("London", 51.5074, -0.1278), _
Array("Sydney", -33.8599, 151.2111))

I reference the data in the locations object elsewhere in the code as follows:

For i = 0 To UBound(locations)
Dim locationName As String
locationName = locations(i)(0)
Dim lat As Double
lat = locations(i)(1)
Dim lng As Double
lng = locations(i)(2)
Next

And this works.

I now want to instead store the data in a table and read that table into the same locations variable. I want the full table with headers and I am using the following.

Set TL = Sheet1.ListObjects("Table1")
Debug.Print TL.ListRows.Count
Dim locations As Variant
locations = TL.Range 'using .Range as I want the headers too

But it fails on locationName = locations(i)(0) fails when I do this with a Run-time error '9' Subscript out of range.

Why is this?

Thanks in advance.
 

Excel Facts

VLOOKUP to Left?
Use =VLOOKUP(A2,CHOOSE({1,2},$Z$1:$Z$99,$Y$1:$Y$99),2,False) to lookup Y values to left of Z values.
Because when you load a table like this, it's a 1-based array meaning the lowest index is 1, not 0. Also, it stores the data in a 2-D array, not an array of arrays. So locations(1,1) would return the heading for column 1, and locations(2,1) would return the first data from column 1.
 
Upvote 0

Forum statistics

Threads
1,223,243
Messages
6,170,964
Members
452,371
Latest member
Frana

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top