22

I want to change the size of the object tables through VBA, I tried modifying the code from MSDN about the listobject.resize method, but I want to dynamically if a data loaded in each row.

The code I'm trying but to no avail:

Sub resizedata()

    Dim ws As Worksheet
    Dim ob As ListObject
    Dim Lrow1 As Long

    Lrow1 = Sheets("db_goods").Cells(Rows.Count, "E").End(xlUp).Row
    Set ws = ActiveWorkbook.Worksheets("db_goods")
    Set ob = ws.ListObjects("Table1")

    ob.Resize Range("A1" & Lrow1)

End Sub

enter image description here

3 Answers 3

24

The problem is Range("A1" & Lrow1) returns a Range of $A$112, because you are passing the Range function the result of the catenation of "A1" & "12".

Try replacing this line:

ob.Resize Range("A1" & Lrow1)

With this one:

ob.Resize ob.Range.Resize(Lrow1)
0
16

There's way avoiding calculating last row:

Sub ResizeListDyn()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects(1)
    tbl.Resize tbl.Range.CurrentRegion
End Sub
2
  • 1
    I believe this answer is much more helpful since I observed that .End(xlUp) will jump to the last row of the table instead of to the last row with actual content in the respective cell. Thanks btw
    – Ben
    Commented May 7, 2019 at 12:55
  • 1
    Not reliable in a few cases e.g. if you have empty row (no data), data above headers etc.
    – Rafał B.
    Commented Jun 1, 2022 at 13:00
8

If you need to resize only the row-dimension:

Dim tbl As ListObject

Set tbl = ActiveSheet.ListObjects("YourTableName")
With tbl.Range
    tbl.Resize .Resize(.CurrentRegion.Rows.Count) 'NOTE: unlike the Range.Resize proprty, the Table.Resize
                                                  'method's argument is a Range object (not a size spec).
End With

Resizing only the column-dimension would be symmetrical:

With tbl.Range
    tbl.Resize .Resize(, .CurrentRegion.Columns.Count)
End With

Not the answer you're looking for? Browse other questions tagged or ask your own question.