Search code examples
excelvba

Application defined or object defined macro error


I have a macro code:

Sub Daily_ACH_Tables()
    ' Daily_ACH_Tables Macro
    Columns("A:H").Select
    Application.CutCopyMode = False
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A:$H"), , xlYes).Name = "Table4"
    ' Moves to the next sheet
    ActiveSheet.Next.Select
    Columns("A:H").Select
    Application.CutCopyMode = False
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A:$H"), , xlYes).Name = "Table5"
    Columns("A:H").Select
End Sub

The data in the rows will change day to day but the headers wont. How can I modify this macro so that no matter the amount of rows or data this macro will work? I did try to use chatgpt and it gave me this macro code as I dont know how to code at all but that code is not working at all and giving an error occurred application defined, or object defined error.

Sub Daily_ACH_Tables()
   Dim ws As Worksheet
   Dim tbl As ListObject
   Dim tblName As String
   Dim lastRow As Long
   On Error GoTo ErrorHandler
   ' Define the worksheet
   Set ws = ThisWorkbook.ActiveSheet
   ' Find the last row with data in column A
   lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
   ' Create table for the data in columns A to H
   Set tbl = ws.ListObjects.Add(xlSrcRange, ws.Range("A1:H" & lastRow), , xlYes)
   ' Assign a name to the table
   tblName = "Table" & ws.ListObjects.Count
   ' Rename the table
   tbl.Name = tblName
   ' Clear any existing filters
   tbl.AutoFilter.ShowAllData
   Exit Sub
ErrorHandler:
   MsgBox "An error occurred: " & Err.Description, vbCritical
End Sub

Solution

  • Here's one way to do it:

    Sub Daily_ACH_Tables()
        Const NUM_SHEETS = 2 '# of sheets to process, beginning with activesheet
        Dim ws As Worksheet, f As Range, n As Long
        
        Set ws = ActiveSheet 'start with the active worksheet
        Do
            n = n + 1 'increment sheet count
            'find the last-used cell in A:H on `ws`
            Set f = ws.Range("A:H").Find(what:="*", searchorder:=xlByRows, _
                                         SearchDirection:=xlPrevious)
            If Not f Is Nothing Then 'sheet has content?
                'create the table...
                ws.ListObjects.Add xlSrcRange, ws.Range("A1:H" & f.Row), , xlYes
            End If
            Set ws = ws.Next              'next worksheet (if any)
            If ws Is Nothing Then Exit Do 'no more sheets!
        Loop While n < NUM_SHEETS
    End Sub
    

    I didn't name the created tables - don't know if that's important for your use case?