问题
I have programmed the following userform in 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
The password variable a = "test"
This password userform itself works perfectly. Now I want to connect it to a button that is already in the sheet. The code behind this button is in the section "ThisWorkbook" in the VBA editor:
Sub Button_Test()
UserForm1.Show
Tabelle2.Range("C3").Value = 1
End Sub
The idea is that the button "Button_Test" is protected by a password that can be entered by the userform. Once the password is correctly entered the macro "Tabelle2.Range("C3").Value = 1" will be conducted.
However, currently I have the issue that the userform responses me with "Password Correct" but does not start the macro "Tabelle2.Range("C3").Value = 1".
How can I tell the userform once the password is entered correct it should jump back to the macro "Button_Test" and continue the procedure?
Thanks for any help.
回答1:
I would work with a boolean value that you will set on true when the Password was correct. You Could make something like this:
Code in Modul or Sheet
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
And in the UserForm you can Put a Code Like that:
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
来源:https://stackoverflow.com/questions/37805593/password-button-and-userform