I\'m trying to refer to a cell in an excel table by using the table header name and the row number using VBA.
How can I do this?
Is there any reason one should avoid using this method?
ThisWorkbook.Worksheets("MyWksht").Range("TableName[ColumnTitle]").Cells(RowNumber)
Seems the simplest answer in my opinion.
It seems to me that @Salam Morcos solution will not give a proper answer. If table starts from cell A2
statment [MyTable[FirstColumnName]].Column
would give value of 2. Proper solution would be:
MsgBox [MyTable].Cells(2, [MyTable].Column-[MyTable[MyColumn]].Column + 1)
Much simpler, and dynamic:
ThisWorkbook.Worksheets("WorkSheet_Name").Range("Table_Name").Rows(Table_row_number).Select
In your example, something like this:
Dim tb As ListObject
'assumes Table is the first one on the ActiveSheet
Set tb = ActiveSheet.ListObjects(1)
MsgBox tb.DataBodyRange.Cells(2, tb.ListColumns("header4").Index)
It is as simple as this. If you call by the name of the column, then the column index will be 1 for that range so:
msgbox ActiveSheet.ListObjects(1).ListColumns("header4").DataBodyRange(2,1).value
If you want to write it short:
[MyTable[header4]].Rows(2)