密码按钮和用户表单

时间:2016-06-14 07:28:02

标签: excel excel-vba macros vba

我在Excel VBA中编写了以下用户格式:

Private Sub CommandButton1_Click()
Password = TextBox1.Text
If Password = a Then
MsgBox "Password Correct.", vbInformation
Unload Me
Else
MsgBox "Password Incorrect. Please try again.", vbCritical
End If
End Sub

密码变量a =“test”

此密码用户表单本身非常有效。现在我想将它连接到工作表中已有的按钮。此按钮后面的代码位于VBA编辑器中的“ThisWorkbook”部分:

Sub Button_Test()
UserForm1.Show
Tabelle2.Range("C3").Value = 1
End Sub

这个想法是按钮“Button_Test”受用户表单输入的密码保护。一旦密码正确输入宏“Tabelle2.Range(”C3“)。值= 1”将进行。

但是,目前我遇到的问题是userform使用“Password Correct”响应我但没有启动宏“Tabelle2.Range(”C3“)。值= 1”。

如果输入密码后如何告诉userform,它应该跳回宏“Button_Test”并继续执行该程序?

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我会使用一个布尔值,当密码正确时,你将设置为true。你可以做这样的事情:

模块或工作表中的代码

Sub Schaltfläche1_Klicken()
'Load funktion Check Password
If UserForm1.checkPassword() = True Then
    'Run this Code when PWD was Correct
    Tabelle1.Range("C3").Value = 1
End If
End Sub

在UserForm中,你可以像这样输入代码:

Private passwordStatus As Boolean

Private Sub CommandButton1_Click()
    Dim a As String
    Dim Password As String

    a = "123"
    Password = TextBox1.Text
    'Set Pawwordstatus at False before Testing
    passwordStatus = False
    If Password = a Then
        MsgBox "Password Correct.", vbInformation
        passwordStatus = True
        Unload Me
    Else
        MsgBox "Password Incorrect. Please try again.", vbCritical
    End If
End Sub

Function checkPassword() As Boolean
  UserForm1.Show
  'Shows the User Form. And after Closing the Form
  'The PasswordStatus Value will be returned and you can check if
  'it is true
  checkPassword = passwordStatus
End Function