0

I would like to create a macro which go through all table of my worksheet and for each of them, create an array with the same name as the table and populate the array with value from the table. I started with this:

Dim tbl as ListObject
For Each tbl In Worksheets(Brand).ListObjects

But I don't see how can I proceed to create a array with my tbl.Name as name of array? is it possible?

2
  • Just use a 2 dymensional array instead. Eg tbl[x][y] where x is the table's index and y are the actual datarows for each and every table. Has the same functionality as naming separate ids and is actually easier to work with Commented Jun 25, 2018 at 9:58
  • Ok thank you for the advice. I already use a 2D table, this would lead to 3D table which are harder to use. I will think on that Commented Jun 25, 2018 at 10:04

2 Answers 2

1

You could use a collection:

Dim coll As New Collection
Dim ws As Worksheet
Dim lo As ListObject

For Each ws In ThisWorkbook.Worksheets
    For Each lo In ws.ListObjects
        coll.Add lo.DataBodyRange.Value, lo.Name
    Next lo
Next ws
Sign up to request clarification or add additional context in comments.

Comments

1

Use a dictionary

You can name an array with table's name as you add them to dictionary.

Dim iDict As Object
Dim tbl As ListObject

Set iDict = CreateObject("Scripting.Dictionary")
For Each tbl In ThisWorkbook.Worksheets("Brand").ListObjects
    iDict.Add tbl.Name, tbl.DataBodyRange.Value
Next

Additionaly you can retrieve an array as

Dim vArr() : vArr = iDict(anytablename)

5 Comments

Add a reference to MIcrosoft Scripting Runtime, then you can write Dim iDict As New Scripting.Dictionary instead of Object and CreateObject.
@ZevSpitz AntiDrondert is using Late Binding so no reference is needed
@Tom And it works, but it is less typesafe than using a reference and strongly-typed variables.
@ZevSpitz You're right on all points, I'm just more used to late binding, since a lot of people are using my modules and they're frustrated if they have to manualy add references, and I don't know how to add them programmaticaly.
@vib500 I should note that using collections is usualy better in terms of perfomance, if I'm not mistaken, so consider trying out Olly's answer as well.

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.