就 UserForms 而言,我是一个完全的初学者(另外,我想说我也是 VBA 的自学初学者)。我正在尝试设置一个用户窗体,您必须在其中输入密码。输入密码后,我希望工作表上出现 4 个按钮。
用户窗体称为“UserForm2”,文本框称为“PASSWORD”,输入按钮称为“确定”
我希望密码为“admin”(占位符)。
我在主工作表上设置了一个名为“CommandButton1”的命令按钮,它使用以下代码打开用户窗体:
Private Sub CommandButton1_Click()
UserForm2.Show
End Sub
现在我打开了用户窗体,我不确定如何实现我的目标,我想要显示的 4 个按钮只是标准的 Excel 按钮,附加了宏。标准 Excel 按钮可以使用吗?或者我必须将它们更改为命令按钮才能隐藏和显示它们?
此外,我正在努力寻找一种方法来输入密码然后读取。
我在网上找到了这个代码:
Sub LOGIN()
Dim PASSWORD As String
PASSWORD = "ADMIN"
'Check if the password is correct
If UserForm2.PASSWORD.Value <> PASSWORD Then
'Display a message and exit the sub-routine if the password is not correct
MsgBox "Sorry, incorrect password. Please try again.", vbOKOnly, "Incorrect Password"
Exit Sub
End If
'The following code will only be executed if the password is correct...
'Close the password input user form now that we don't need it
Unload UserForm2
End Sub
但是,我不确定这是如何工作的以及如何让它为我工作。
总而言之,我想单击一个按钮打开用户窗体,然后输入密码,然后单击用户窗体上的确定按钮,然后出现 4 个按钮。
非常感谢任何帮助。
在测试之前,我将 4 个(ActiveX 命令)按钮设置为
.Visible = False
。
然后使用您的代码的另一个按钮来显示用户窗体。
当您在设计模式中右键单击“确定”按钮时,您可以选择进入代码,其看起来像(带有您需要的代码):
Private Sub OK_Click()
Dim pwd As String, ws As Worksheet
pwd = "ADMIN"
'Check if the password is correct
If UserForm2.PASSWORD.Value <> pwd Then
'Display a message and exit the sub-routine if the password is not correct
MsgBox "Sorry, incorrect password. Please try again.", vbOKOnly, "Incorrect Password"
Exit Sub
End If
'The following code will only be executed if the password is correct...
'Close the password input user form now that we don't need it
Set ws = ThisWorkbook.Worksheets("YourSheet")
Dim i As Long
For i = 2 To 5 'my extra "invisible" buttons were called btn2, etc.
ws.Shapes.Item("btn" & i).Visible = True
Next i
Unload UserForm2
End Sub
如果用户输入“ADMIN”,这应该使它们可见,“admin”在这里不起作用,除非您不关心密码中的大写字母,然后只需使用
UCase(UserForm2.PASSWORD.Value)
希望这是清楚的:)