应用程序定义或对象定义的宏错误

问题描述 投票:0回答:1

我有一个宏代码:

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

行中的数据会每天发生变化,但标题不会。如何修改此宏,以便无论行数或数据量多少,此宏都可以工作?我确实尝试使用 chatgpt,它给了我这个宏代码,因为我根本不知道如何编码,但该代码根本不起作用,并给出了发生应用程序定义的错误或对象定义的错误。

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
excel vba
1个回答
0
投票

这是一种方法:

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 ws Is Nothing Then Exit Do 'no more sheets!
    Loop While n < NUM_SHEETS
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.