文件受保护时运行的宏

时间:2019-02-01 13:02:44

标签: excel vba plot

我做了宏来创建图形,但是需要对文件密码进行保护。

当然,当我保护文件时,宏将停止工作。

我将以下内容插入我的代码中以取消保护文件,运行代码,然后再次保护文件。因为我的代码是一个函数,所以我必须创建两个子过程,这也许是该技巧无法起作用的原因。

有什么主意我可以解决这个问题吗?

Option Explicit
Sub protection()

    Worksheets("Sheet1").Unprotect "abc123"

End Sub

Function (here is my function code)

End Function

Sub protection2()
Worksheets("Sheet1").protect "abc123"

End Sub

2 个答案:

答案 0 :(得分:2)

我猜您想启动一个子过程来完成这项工作。我的示例取消了对工作表的保护,让该函数发挥作用并保护工作表。

Option Explicit
Sub protection()

    Worksheets("Sheet1").Unprotect "abc123"

    Call Function (here may be values for your arguments)

    Worksheets("Sheet1").protect "abc123"
End Sub

Function (here may be prameters)

    the function code belongs here

End Function

答案 1 :(得分:1)

在受保护的工作表上,您无法更改已锁定的单元格。您可能会不喜欢附带的代码:

Option Explicit

Sub SheetSetup()
    Range("B3:C7").Locked = False
    Range("E3:F7").Locked = True   'This is default
End Sub

Sub Sample_ProtectedSheet()
    ClearValues
    ChangeAllValues_on_ProtectedSheet
    MsgBox ("Only values in ""B4:C7"" are set to ""yes""!")
End Sub

Sub Sample_UnprotectedSheet()
    ClearValues
    ChangeAllValues_on_UnprotectedSheet
    MsgBox ("All values set to ""yes""!")
End Sub


Function ChangeAllValues_on_UnprotectedSheet()
    Call Unprotect
    On Error Resume Next
    Range("B4:C7").Value = "yes"
    Range("E4:F7").Value = "yes"
    On Error GoTo 0
End Function

Function ClearValues()
    Call Unprotect
    On Error Resume Next
    Range("B4:C7").Value = ""
    Range("E4:F7").Value = ""
    On Error GoTo 0
End Function

Function ChangeAllValues_on_ProtectedSheet()
    Call Protect
    On Error Resume Next
    Range("B4:C7").Value = "yes"
    Range("E4:C7").Value = "yes"
    On Error GoTo 0
End Function

Sub Protect()
    Worksheets("Sheet1").Protect "abc123"
End Sub

Sub Unprotect()
    Worksheets("Sheet1").Unprotect "abc123"
End Sub

enter image description here

相关问题