编译错误:预期结束小组
我有一个macros分配给一个形状,并希望密码保护这个macros,所以当形状被点击时出现一个popup框要求passwork,理想情况下,我想通过用户forms做到这一点。
我已经看了这个问题: 你如何密码保护Excel的VBAmacros运行,并已经做了我相信回答者说,所以我的代码如下:
Sub EmailExtract() UserForm1.Show ***Code for the macro then follows*** End Sub
然后点击button的用户表单:
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
有人可以告诉我我做错了什么吗?
- 您必须closures
If statement
与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
来收集和检查密码值。
确保您的密码保护您的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
第二次更新:
这样你创build一个Sub
来调用UserForm
然后validation密码input,然后调用sub EmailExtract()
并运行所需的代码。
使用UserForm
使用密码保护的方法如下所示:
显示UserForm
(被你的形状调用):
Sub UserFormShow() UserForm1.Show End Sub
做密码validation:
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