在下面的代码中,我有一个日志表,用于存储人们打开工作簿的时间。当它打开并存储日志后,我希望它保存起来,以使信息不会丢失。这段代码可以正常工作一段时间,但是现在我立即运行它时就抛出了运行时错误,说
“运行时错误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
预期结果应该是整个打开事件均正常运行,并且打开该信息的人员将保存到日志表中。
答案 0 :(得分:0)
尝试一下:
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