我有一个宏指定给一个形状,并希望密码保护这个宏,以便在单击形状时出现一个弹出框询问一个passwork,理想情况下我想通过用户表单执行此操作。
我看过这个问题:How do you password protect excel VBA macro from running并完成了我认为回答者所说的话,所以我的代码如下:
Sub EmailExtract()
UserForm1.Show
***Code for the macro then follows***
End Sub
然后单击按钮的用户表单:
Private Sub CommandButton1_Click()
If TextBox1.Value = "Password" Then 'Replace Password by your custom password
Sub EmailExtract() 'This is the sub that was being called by your button.
Else
MsgBox "You are not allowed to launch the macro"
End If
Exit Sub
End Sub
但是当我尝试运行此操作时,我会收到错误Compile error: Expected End Sub
:If TextBox1.Value = "Password" Then
有人可以告诉我我做错了吗?
答案 0 :(得分:3)
End If
Exit Sub
关闭Sub
Sub
内拨打End Sub error
,这会引发EmailExtract
您只需要输入Private Sub CommandButton1_Click()
If TextBox1.Value = "Password" Then 'Replace Password by your custom password
EmailExtract 'This is the sub that was being called by your button.
Else
MsgBox "You are not allowed to launch the macro"
Exit Sub
End If
End Sub
见下面的代码:
InputBox
<强>更新强>
这是一种不同的密码保护方法,只需使用UserForm
代替Sub EmailExtract()
Dim Message As String, Title As String, Password As String
Message = "Enter the macro password" ' Set prompt.
Title = "Macro Password" ' Set title.
Password = InputBox(Message, Title)
If Password = "Password Here" Then
''***Code for the macro then follows***
Else
MsgBox "You are not allowed to launch the macro"
Exit Sub
End If
End Sub
来收集和检查密码值。
确保您的密码保护您的VBA代码,否则任何知道如何检查代码并从代码中获取密码的人。
Sub
第二次更新:
这样您就可以创建一个UserForm
来调用sub EmailExtract()
,然后验证密码输入,然后调用UserForm
并运行所需的代码。
使用UserForm
密码保护的方式如下:
显示Sub UserFormShow()
UserForm1.Show
End Sub
(由你的形状调用):
Private Sub CommandButton1_Click()
If TextBox1.Value = "Password" Then 'Replace Password by your custom password
EmailExtract 'The new sub your going to call
Else
MsgBox "You are not allowed to launch the macro"
Exit Sub
End If
End Sub
进行密码验证:
Sub EmailExtract()
***Code for the macro then follows***
end sub
运行您的代码(新子代码):
Inline-block