我对VBA很陌生,我非常感谢这方面的支持。
我正在写一个简单的代码,要求用户输入'密码'。密码列表在VBA中是硬编码的。如果用户输入的密码与VBA中的硬编码相匹配,那么它会将其放在单元格'B2'上,如果错误,则用户将收到密码错误的错误消息。
到目前为止我的代码是:
Sub Password()
Dim Password As String
Dim Msg As String
Dim List(Password1, Password2) As String
Msg = "please enter password"
Password = InputBox(Msg)
If Password <> List Then
MsgBox "Incorrect Password!"
ActiveSheet.Range("B2").Value = Password
End Sub
我不确定我哪里出错了?
非常感谢
答案 0 :(得分:3)
我建议使用Collection。 这是创建集合并向其添加项目的方法:
Dim pwList As New Collection
pwList.Add "TestPass1"
pwList.Add "TestPass2"
不幸的是,VBA Collection没有默认函数来检查字符串是否是它的一个元素。此函数可用于检查集合是否包含字符串(只需在代码中的某处粘贴此函数):
Public Function CollectionContains(col As Collection, val As String) As Boolean
Dim item As Variant
For Each item In col
If item = val Then
CollectionContains = True
Exit Function
End If
Next item
CollectionContains = False
End Function
现在,这就是您的代码的样子:
Sub Pw()
Dim Password As String
Dim pwList As New Collection
pwList.Add "TestPass1"
pwList.Add "TestPass2"
Password = InputBox("please enter password")
If CollectionContains(pwList, Password) Then
ActiveSheet.Range("B2").Value = Password
Else
MsgBox "Incorrect Password!"
End If
End Sub