2015-08-20 86 views
2

我有一个宏分配给一个形状,并希望密码保护这个宏,以便当单击形状时出现一个弹出框要求passwork,理想情况下,我想通过用户表单。编译错误:预期结束Sub

我已经看过了这个问题: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 SubIf TextBox1.Value = "Password" Then

是否有人可以告诉我我做错了什么?

+0

你必须在'Exit Sub'后用'End If'关闭'If语句'' – DragonSamu

+0

感谢您的建议,我刚刚尝试过,而且我仍然收到错误 –

+0

难道你没有无限循环?你点击用户窗体上的按钮 - >启动子窗口'emailextract' - >打开我们之前两步的用户窗体 – psychicebola

回答

3
  • ,你必须关闭If statementEnd IfExit Sub
  • 后要调用Sub其抛出End Sub error你只需要把内SubEmailExtract
下面

见代码:

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来收集和检查密码值。

确保您的密码保护您的VBA代码,否则任何知道如何检查代码并从代码中获取密码的人。

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 

月2日更新:

这样你创建一个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 
+0

谢谢!这非常出色!我现在得到的唯一一个错误,我认为与@ psychicebola在评论中指出的有关,当密码输入错误时:'运行时错误400:已经显示的窗体;无法显示模态“出现,有没有一种方法可以使用用户窗体并在宏内调用它而不存在循环? –

+0

所以当点击形状时,它会运行一个调用用户表单的宏,然后你需要输入正确的密码? – DragonSamu

+0

是的,这是正确的,所以它会依次点击按钮>开始宏>打开用户窗体>如果密码正确回到宏 –