保护其他工作簿的共享

时间:2020-05-06 12:17:23

标签: excel vba

我正在尝试为excel工作簿创建新的保护,因为您知道excel的保护非常弱。 现在,我需要为共享设置保护,这将在另一个工作簿而不是activeworkbook上完成

假设代码在Test.xlsm中,我需要保护已关闭的工作簿Sample.xlm 这是我创建的代码

Dim wb As Workbook

Sub DoProtectionTask()
    Dim sPath As String
    sPath = ThisWorkbook.Path & "\Sample.xlsm"
    Set wb = Workbooks.Open(sPath)
    ProtectSharing True, "123", "456"
    wb.Close True
End Sub

Private Sub ProtectSharing(ByVal b As Boolean, ByVal sPass1 As String, ByVal sPass2 As String)
    Dim x
    If b Then
        On Error GoTo Skipper
        Application.DisplayAlerts = False
        Application.EnableEvents = False
            wb.ProtectSharing Password:=sPass1, SharingPassword:=sPass2
Skipper:
        Application.DisplayAlerts = True
        Application.EnableEvents = True
    Else
        x = InputBox("Enter Admin Password")
        If x <> sPass1 Then MsgBox "Invalid Password. Contact The Workbook Owner", vbExclamation: Exit Sub
        wb.UnProtectSharing sPass1
    End If
End Sub

代码有效且出错,但是在运行代码后打开Sample.xlsm时,我发现工作簿没有共享保护。尽管此方法适用于ThisWorbook或ActiveWorkbook

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解得很好,但是我认为此代码wb.UnProtectSharing sPass1应该看起来像:wb.UnProtectSharing sPass2

所有代码:

Dim wb As Workbook

Sub DoProtectionTask()
    Dim sPath As String
    sPath = ThisWorkbook.Path & "\Sample.xlsm"
    Set wb = Workbooks.Open(sPath)
    ProtectSharing True, "123", "456"
    wb.Close True
End Sub

Private Sub ProtectSharing(ByVal b As Boolean, ByVal sPass1 As String, ByVal sPass2 As String)
    Dim x
    If b Then
        On Error GoTo Skipper
        Application.DisplayAlerts = False
        Application.EnableEvents = False
            wb.ProtectSharing Password:=sPass1, SharingPassword:=sPass2
Skipper:
        Application.DisplayAlerts = True
        Application.EnableEvents = True
    Else
        x = InputBox("Enter Admin Password")
        If x <> sPass1 Then MsgBox "Invalid Password. Contact The Workbook Owner", vbExclamation: Exit Sub
        wb.UnProtectSharing sPass2
    End If
End Sub