Compile error: Expected End Sub

Compile error: Expected End 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

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

  • 你必须在 Exit Sub
  • 之后用 End If 关闭 If statement
  • 而你在 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

第二次更新:

通过这种方式,您可以创建一个 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