Search code examples
excelvbalistobject

VBA saving tbl.ColumWidth as variable returns error 438?


I'm trying to compare the current columnwidth to the autofit columnwidth like this:

Option Explicit
    Dim Tbl As Object
    Dim Col As Integer
    Dim I As Integer
    Dim OldColumnWidth As Integer
    Dim NewColumnWidth As Integer
Private Sub WorkSheet_Change(ByVal Target As Range)
    'On Error GoTo ErrHandler

    Set Tbl = ListObjects("RuimteTabel")
    Col = Tbl.DataBodyRange.Columns.Count
    For I = 1 To Col
        OldColumnWidth = Tbl.ListColumn(I).Range.ColumnWidth
        NewColumnWidth = Tbl.DataBodyRange.Column.AutoFit

        If NewColumnWidth < OldColumnWidth Then
            'Tbl.DataBodyRange = OldColumnWidth
        Else
            'Tbl.DataBodyRange = NewColumnWidth
        End If
    Next I

But whenever its at the OldColumnWidth = Tbl.ListColumn(I).Range.ColumnWidth line it gives the error:
Object doesn't support this property or method

I understand why the error occurs, but I do not see anything wrong with my code / how to fix the error


Solution

  • Your issue is in your syntax

    OldColumnWidth = Tbl.ListColumns(I).Range.ColumnWidth
    

    You're missing an s on the end of ListColumns.

    I'd also recommend Dimming your variables as Long instead of Integer