19

I am trying to write some VBA in Excel that can take the name of a table (list object) as a parameter and return the number of rows.

The following works, but isn't allowing me to pass in a string with the table name.

MsgBox ([MyTable].Rows.Count)

The following gives the error:

Object required

v_MyTable = "MyTable"
MsgBox (v_MyTable.Rows.Count)

The following gives the error:

Object variable or With block variable not set

v_MyTable_b = "[" & "MyTable" & "]"
MsgBox(v_MyTable_b.Rows.Count)

I also tried working with ListObjects, which I am new to. I get the error:

Object doesn't support this property or method

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox(tbl.Rows.Count)

Thanks for any help!

3 Answers 3

36

You need to go one level deeper in what you are retrieving.

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox tbl.Range.Rows.Count
MsgBox tbl.HeaderRowRange.Rows.Count
MsgBox tbl.DataBodyRange.Rows.Count
Set tbl = Nothing

More information at:

ListObject Interface
ListObject.Range Property
ListObject.DataBodyRange Property
ListObject.HeaderRowRange Property

Sign up to request clarification or add additional context in comments.

2 Comments

Note that if the table is empty, tbl.DataBodyRange.Rows.Count throws an error
Instead tbl.listrows.count can be used to get the number of rows even if the table is empty. This would not throw any error in a code
5

You can use this:

    Range("MyTable[#Data]").Rows.Count

You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:

    If WorksheetFunction.CountA(Range("MyTable[#Data]"))

3 Comments

How does this improve on the accepted answer from over 1 year ago?
Well, I'm sorry that @Jalal anwser was late for you, but I'm really glad he posted it!
[#data] can be omited. i.e. Range("MyTable").Rows.Count can be used. This is even better: Range("MyTable").ListObject.ListRows.Count as it will return 0 if the table has no rows (a variation of what @Kanike mentioned in his comment above).
1

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

Comments

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.