我正在使用Workbook_BeforeSave更新excel 2010中锁定工作表上的某些单元格。使用ctrl-s保存时,子程序可以正常工作,但在vba中使用.Save时不会解锁工作表。
的ThisWorkbook(代码)
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim MyPassword As String
MyPassword = "password"
ActiveWorkbook.Worksheets("Sheet1").Unprotect (MyPassword)
ActiveWorkbook.Worksheets("Sheet1").Range("A1").Value = Now
ActiveWorkbook.Worksheets("Sheet1").Range("A2").Value = ThisWorkbook.BuiltinDocumentProperties("Author")
ActiveWorkbook.Worksheets("Sheet1").Protect (MyPassword)
End Sub
模块1(代码)
Sub SaveMe()
ActiveWorkbook.Save
End Sub
我有一个调用SaveMe()的按钮。 SaveMe()保存文档,激活Workbook_BeforeSave。 Worsheet无法取消保护,在写入A1时导致错误。
错误说明:
Run-time error '1004':
Application-defined or object-defined error
答案 0 :(得分:1)
这对我有用,但不是很优雅。我没有找到一个单独的模块来进行无保护和写作。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
UnlockWorksheets
With ThisWorkbook.Worksheets("Sheet1")
.Range("A1").Value = Now
.Range("A2").Value = ThisWorkbook.BuiltinDocumentProperties("Author")
End With
LockWorksheets
End Sub
Sub SaveMe()
UnlockWorksheets
ThisWorkbook.Save
LockWorksheets
End Sub
Sub UnlockWorksheets()
ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="password"
End Sub
Sub LockWorksheets()
ThisWorkbook.Worksheets("Sheet1").Protect Password:="password"
End Sub
答案 1 :(得分:0)
为什么不在保存之前放置'模块进入一个新的子程序并具有之前的近距离调用
EG。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Call SomeSub
End Sub
sub someSub()
'Code here
end sub
sub Button()
call SomeCub
activeworkbook.save
end sub