对 MS 上的命令按钮编码有挑战 Excel VBA

Having challenges to code command button on MS Excel VBA

我是 VBA 的新手。

我有一个 protected/locked 带密码的工作表。

我有一个 CommandButton,单击它会加载一个用于将记录输入到工作表中的用户窗体。

我希望在单击命令按钮时,在加载用户窗体之前提示用户输入取消保护密码(用于 protect/lock 工作表)。

如果用户输入正确的取消保护密码,则加载用户窗体。如果用户输入不正确的取消保护密码,将显示 MsgBox 并且不会加载用户窗体。

问题是单击命令按钮时,如果用户单击 "Cancel" 按钮,系统将提示用户输入取消保护密码(Excel 的内置取消保护对话框) ,用户窗体仍然加载。这不是我想要的。我想要的是:如果单击 "Cancel" 按钮,则显示 MsgBox,并且不会加载用户窗体。

下面是我的命令按钮代码:

Private Sub CommandButton1_Click()
    On Error Resume Next
    ActiveSheet.Unprotect
    If Err <> 0 Then
    MsgBox:
        MsgBox "Incorrect Password. Unlock Failed!"
    Else
        UserForm3.Show
    End If
End Sub

这是我的代码

Userform1 布局

注意:Textbox1 中有一个 PasswordChar 属性,将其设置为 * 这样人们就不会看到正在输入的密码。

模块上命令按钮的代码:

这将显示用于密码验证的用户表单。

Sub Button1_Click()

UserForm1.Show

End Sub

Userform1 的代码

这是您将密码分配给密码变量的地方。

命令按钮 1,这将检查文本框 1 中的密码是否与存储的密码相同。如果它相同,它会取消保护 sheet 和附加消息,如果不相同,那么它将 msgbox "incorrect password"

Command Button2 将成为您的取消按钮,这将隐藏 userform1

Private Sub CommandButton1_Click()

Password = "yourpassword"

If UserForm1.TextBox1.Value = Password Then
    Worksheets("Sheet2").Unprotect (Password)
    'this is for unprotecting sheets
    'or you can also use it to show Userform2
    MsgBox "Sheet now unprotected or Userform2 now shows"
    UserForm1.Hide
    Userform2.Show

Else
    MsgBox "Incorrect Password"
End If

End Sub

命令按钮 2

Private Sub CommandButton2_Click()

UserForm1.Hide

End Sub