debugging 为什么使用简单的VBA宏时总是出现应用程序定义或对象定义的错误?

p4tfgftt  于 2023-01-21  发布在  其他
关注(0)|答案(2)|浏览(117)

我正在创建一个宏,以简化我每天要做的事情。此宏背后的思想是从父报表复制7个工作表,打开新工作簿,粘贴并硬编码数据,将其保存到桌面并关闭新工作簿。
当我调试和测试我的代码时,我遇到了一个问题,我不知道为什么会发生。如果我 Boot windows并在excel工作簿中第一次运行宏,我第一次为7个报告运行时没有问题。当我尝试添加代码或修复问题并再次运行代码时,问题出现。我一直收到“运行时错误”1004“应用程序定义或对象定义的错误”“。
我正在尝试调试,当我按F8进行调试和单步执行代码时,它似乎在第4步附近挂起,当我多次运行它时,它试图关闭。我正在学习和使用Leila Gharani的课程,但我不认为我在课程中了解了这么多。如果有人能帮助我,让我能理解这个概念,我将非常感激。
谢谢

'1. Select Parent Report and select BD Tab
Workbooks("Parent Report").Activate
Worksheets("BD").Select

'2. Select all cells from BD tab, open new workbook , paste data, and hardcode it.
Cells.Select
Cells.Copy
Workbooks.Add
Range("A1").PasteSpecial xlPasteAll
Cells.Select
Cells.Copy
Range("A1").PasteSpecial xlPasteValues
Cells.EntireRow.AutoFit

'3. Rename worksheet to BD and cell "A2" to BD.
ActiveWorkbook.ActiveSheet.Name = "BD"
Range("A2").Value = "BD"
Range("A1").Select

'4. Save current flash report to local drive, with monthly naming format and close it.
ActiveWorkbook.SaveAs "C:\Users\mylocaldriveinfo\Desktop\Flash Reports" & "\BD Monthly Reporting - Preliminary " & Format(Date, "mmm") & " " & Format(Date, "yyyy")
ActiveWorkbook.Close
fwzugrvs

fwzugrvs1#

我刚想通。这是我工作中的一个驱动器给了我一个问题。我禁用了它,因为我从来没有使用它,这样做我就无法复制错误。
我确信这段代码不是最佳实践,但它目前是有效的。

qmelpv7a

qmelpv7a2#

Option Explicit
Sub CopySheets()

    Const FOLDER = "C:\Users\mylocaldriveinfo\Desktop\Flash Reports\BD Monthly Reporting -"

    Dim wbNew As Workbook, wbMaster As Workbook, sht, n As Long

    Set wbMaster = ThisWorkbook

    ' create new workbook
    Set wbNew = Workbooks.Add(1) ' 1 sheet
    n = 1

    For Each sht In Array("BD", "Sheet2", "Sheet3", "Sheet4", _
                      "Sheet5", "Sheet6", "SHeet7") ' 7 sheet names
        
        wbMaster.Sheets(sht).Copy After:=wbNew.Sheets(n)
        n = n + 1
        With wbNew.Sheets(n)
            .UsedRange.Value = .UsedRange.Value
            .Range("A2") = sht
        End With
    Next
    
    With wbNew
        ' delete blank sheet
        Application.DisplayAlerts = False
        .Sheets(1).Delete
        Application.DisplayAlerts = True
    
        ' save
        .SaveAs Filename:=FOLDER & Format(Date, "mmm yyyy")
        .Close
    End With
    MsgBox "Done", vbInformation
      
End Sub

相关问题