一个按钮,用于保护所有工作表,并使用密码和取消保护的按钮

时间:2017-11-06 16:48:17

标签: excel vba excel-vba

我有一个包含大约180个工作表的工作簿。

我正在尝试创建2个宏:

1)点击按钮

保护所有工作表

2)单击按钮取消保护所有工作表,但要求用户输入密码

我已经在这里......

Sub Protect()

Dim ws As Worksheet
Dim pwd As String

pwd = "xyz" ' Put your password here
For Each ws In Worksheets
   ws.Protect Password:=pwd, UserInterfaceOnly:=True
Next ws

End Sub

并取消保护...

Sub UnProtect()

Dim ws As Worksheet
Dim pwd As String

pwd = "xyz" ' Put your password here
For Each ws In Worksheets
    ws.UnProtect Password:=pwd
Next ws

End Sub

Protect宏工作正常。

UnProtect宏保护所有工作表,但我需要它来询问用户密码。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

Sub UnProtect()

Dim ws As Worksheet
Dim pwd As String
Dim myValue As Variant
pwd = "xyz" ' Put your password here
myValue = InputBox("What is the password?")
If myValue = pwd Then
    For Each ws In Worksheets
        ws.UnProtect Password:=pwd
    Next ws
Else
    'do nothing or msgbox
End If

End Sub