Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to a structured table without referring to its sheet in VBA

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?

like image 273
Lun Avatar asked Dec 05 '25 22:12

Lun


2 Answers

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/

like image 61
Lun Avatar answered Dec 08 '25 14:12

Lun


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

enter image description here

like image 21
Michal Rosa Avatar answered Dec 08 '25 14:12

Michal Rosa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!