Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to Excel cell in Table by header name and row number

Tags:

excel

vba

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?

enter image description here

like image 679
Ole Henrik Skogstrøm Avatar asked Sep 15 '13 10:09

Ole Henrik Skogstrøm


People also ask

How do you reference a cell in a table in Excel?

When you create an Excel table, Excel creates a default table name (Table1, Table2, and so on), but you can change the table name to make it more meaningful. Select any cell in the table to show the Table Tools > Design tab on the ribbon. Type the name you want in the Table Name box, and press Enter.

How do you reference a cell by row and column number?

The Excel ADDRESS function returns the address for a cell based on a given row and column number. For example, =ADDRESS(1,1) returns $A$1. ADDRESS can return an address in relative, mixed, or absolute format, and can be used to construct a cell reference inside a formula.

How do I reference a row and a column in Excel?

Excel's INDEX function allows users to reference values in a range of data (or array of data) by their column and row number position within that range. As a simple example, the formula =INDEX(A1:F10, 4,4) would return the value in the fourth row of the fourth column in that specified data range.

How do you reference a cell row number in Excel?

The Excel ROW function returns the row number for a reference. For example, ROW(C5) returns 5, since C5 is the fifth row in the spreadsheet. When no reference is provided, ROW returns the row number of the cell which contains the formula.


3 Answers

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)
like image 166
brettdj Avatar answered Oct 11 '22 11:10

brettdj


A shorter answer is:

MsgBox [MyTable].Cells(2, [MyTable[MyColumn]].Column)

Much cleaner and easier!

like image 17
All4Peace Avatar answered Oct 11 '22 11:10

All4Peace


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.

like image 7
Mike Lasch Avatar answered Oct 11 '22 10:10

Mike Lasch