【问题标题】:Having challenges to code command button on MS Excel VBA在 MS Excel VBA 上编写命令按钮时遇到挑战
【发布时间】:2017-08-02 17:45:01
【问题描述】:

我是 VBA 新手。

我有一个使用密码保护/锁定的工作表。

我有一个命令按钮,单击它时会加载一个用户窗体,用于将记录输入到工作表中。

我希望它在单击命令按钮时提示用户在加载用户窗体之前输入解除保护密码(用于保护/锁定工作表)。

如果用户输入正确的解除保护密码,则加载用户窗体。如果用户输入了错误的解除保护密码,则会显示一个 MsgBox,并且不会加载 UserForm。

问题是当点击CommandButton时,会提示用户输入解除保护密码(Excel的内置解除保护对话框),如果用户点击“取消”按钮,用户窗体仍然加载。这不是我想要的。我想要的是:如果单击“取消”按钮,则会显示 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

【问题讨论】:

    标签: vba userform


    【解决方案1】:

    这是我的代码

    Userform1 布局

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

    模块上命令按钮的代码:

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

    Sub Button1_Click()
    
    UserForm1.Show
    
    End Sub
    

    Userform1 的代码

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

    Command Button1,这将检查 textbox1 中的密码是否与存储的密码相同。如果相同,则使用附加消息取消对工作表的保护,如果不同,则将 msgbox “密码错误”

    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
    

    【讨论】:

      猜你喜欢
      • 2012-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      相关资源
      最近更新 更多