导致有关 ActiveWorkbook.Save 的运行时错误的代码在我的 Workbook_Open() 事件中未触发



在下面的代码中,我有一个日志表,用于存储人们何时打开工作簿。当它打开并存储日志后,我希望它保存,以免丢失信息。这段代码在一段时间内工作正常,但是当我现在运行它时,它只是现在抛出了一个运行时错误,说

"运行时错误 1004 - 应用程序定义或对象定义的错误">

代码如下

Option Explicit
'creating log sheet entry for when workbook is opened
Private Sub Workbook_Open()
    Dim uName As String
    Dim LastRow As Long
    uName = Environ("username")
    Sheet9.Unprotect ("Unprotect")
    LastRow = Sheets("Log Sheet").Range("A65536").End(xlUp).Row
    Sheets("Log Sheet").Cells(LastRow + 1, 1) = uName
    Sheets("Log Sheet").Cells(LastRow + 1, 2) = "Opened"
    Sheets("Log Sheet").Cells(LastRow + 1, 3) = Now()
    ThisWorkbook.Worksheets("Log Sheet").Range("A:A,B:B,C:C").EntireColumn.AutoFit
    Sheet9.Protect ("Unprotect")
    Worksheets("Permitting Summary by FY").Activate
    ActiveWorkbook.Save
End Sub

预期结果应该是整个打开事件运行无误,并且打开它的信息的人将保存到日志表中。

试一试:

Private Sub Workbook_Open()
    Dim wb As Workbook
    Dim uName As String
    Dim sPassword As String
    Dim LastRow As Long
    Set wb = ThisWorkbook
    uName = Environ("username")
    sPassword = "Unprotect"
    With wb.Worksheets("Log Sheet")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        .Unprotect sPassword
        .Cells(LastRow + 1, "A").Value = uName
        .Cells(LastRow + 1, "B").Value = "Opened"
        .Cells(LastRow + 1, "C").Value = Now()
        .Range("A:C").EntireColumn.AutoFit
        .Protect sPassword
    End With
    wb.Worksheets("Permitting Summary by FY").Activate
    wb.Save
End Sub

最新更新