Home » excel » excel – VBA. Rezise table with dynamic last column

excel – VBA. Rezise table with dynamic last column

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am struggling with what should be a simple thing to do. How to resize the table which has a dynamic last column?

Sub rezise_table()
Dim lcol As Long
lcol = ActiveSheet.ListObjects("tblN").DataBodyRange.Columns.Count
        ActiveSheet.ListObjects("tblN").Resize Range("A1" & lcol)
End Sub

This gives a Run-time error 1004 – “wrong align error”. I understand I that the code does not know the last row, but how to state it when the last column is dynamic? Searching gave me no similar cases, which is wierd, because it should be a rather common case? Perhaps i search with wrong keywords…
Help appreciated.

How to&Answers:

DataBodyRange.Columns will already give you the columns in the table. So why resize it to that? I think you want to find the actual column in the worksheet and not the table?

Also Range("A1" & lcol) in your actual code is incorrect. If your last column is 10 then "A1" & lcol becomes A110. See the code below.

Is this what you are trying? I am assuming that row 1 of the activesheet has the headers.

Sub rezise_table()
    Dim lcol As Long, lRow As Long
    Dim lastCol As String
    Dim ws As Worksheet

    Set ws = ActiveSheet

    With ws
        lcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        lRow = 3 '<~~ 2 rows + 1 Header row

        lastCol = Split(.Cells(, lcol).Address, "$")(1)

        .ListObjects("tblN").Resize .Range("A1:" & lastCol & lRow)
    End With
End Sub

enter image description here

Answer:

My final working code for reference (takes the table name at A1. Table itself starts at row 3, ends at row 5):

Sub clearandresize()
Dim tblN As String, lcol, lrow As Long, ws As Worksheet
Set ws = ActiveSheet
tblN = ws.Range("A1")
ActiveSheet.ListObjects(tblN).AutoFilter.ShowAllData
Range(tblN).Select
    Selection.ClearContents
    With ws
        'lcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        lcol = ws.ListObjects(tblN).DataBodyRange.Columns.Count
        lrow = 5 '<~~ 2 rows + 1 Header row
        lastCol = Split(.Cells(, lcol).Address, "$")(1)
        .ListObjects(tblN).Resize .Range("A3:" & lastCol & lrow)
    End With
    Range("A1").Select
Application.CutCopyMode = False
End Sub