3

In VBA I know that I can refer to a structured table via this way:

  Set Tbl = Sheets("MySheetName").ListObjects("MyTblName")

Then do Tbl.XXX where .XXX can be .Name, .Range, etc.

However, I want to refer to this table without referring to the Sheet name, so that the macro does not break if the sheet name changes.

Is this possible?

0m3r
  • 12,286
  • 15
  • 35
  • 71
Lun
  • 428
  • 4
  • 20

4 Answers4

3

After some research I found something that is not a perfect solution. You can make use of the Range function in VBA like this:

Set tbl = Range("TableName[#All]")

However this is not a ListObject but a Range. You can also do other references like:

the body of the structured table (excluding headers)

Range("TableName")

Column called "MyColumn" of the body

Range("TableName[MyColumn]")

etc.

Then you call something like: tbl.ListObject to refer to the structured table where the range is found.

The cool thing is that Range() will always work on the ActiveWorkbook, so you can be in WorkBook B and open a macro in Workbook A and it will still run on Workbook B

Source: https://peltiertech.com/structured-referencing-excel-tables/

Lun
  • 428
  • 4
  • 20
1

Why not refer to the sheet's "internal" name instead of its visible name?

enter image description here

Michal Rosa
  • 2,459
  • 2
  • 15
  • 28
0

If your table is on the ActiveSheet, you can use it like:

Set Tbl = ActiveSheet.ListObjects("MyTblName")
BenderIO
  • 411
  • 4
  • 11
  • What if it's not on the active sheet? – SJR Nov 01 '18 at 10:09
  • 1
    I don't know if I can call it a "good pratice" but when I work with heavy VBA project. I assign all my sheets names in a separate module as public variable with others constants. After that, if a sheet name change I don't have to recode all the project and the good sheet stay activated if correctly updated in the declaration module. (I don't see how to avoid activation. Some basic function are very capricious with this, like the simple "Range") – BenderIO Nov 01 '18 at 12:47
0

If you would like to refer to a table (name "tbl_Function") in an unknown worksheet, here is what you can do:

Set rng4= Range("tbl_Function[#All]")                      ' range of table
sh = rng4.Parent.Name                                      ' name of the worksheet where the table is placed
tbl = Sheets(sh).ListObjects("tbl_Function").Range.Value   ' take the whole table

Hope it helps. Piotr

Piotr
  • 1