0

我正在使用 Workbook_BeforeSave 更新 excel 2010 中锁定工作表上的一些单元格。使用 ctrl-s 保存时,子例程按需要工作,但在 vba 中使用 .Save 时不会解锁工作表。

本工作簿(代码)

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
4

2 回答 2

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
于 2013-01-22T01:16:18.563 回答
0

为什么不将“保存前”模块放入一个新的子例程并在关闭前调用

例如。

    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
于 2013-01-18T23:36:48.763 回答