3

I am very new to VBA and I would very much appreciate support in this.

I am writing a simple code that asks a user to input a 'password'. The list of passwords are hard-coded in VBA. If the user inputs a password that matches what was hard-coded in VBA, then it will put it on cell 'B2', if it is wrong, then the user will get an error message that the password was wrong.

My code so far is:

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

I am not sure where I am going wrong?

Many thanks

1 Answer 1

3

I would suggest using a Collection. This is how to create a collection and add items to it:

Dim pwList As New Collection
pwList.Add "TestPass1"
pwList.Add "TestPass2"

Unfortunately, the VBA Collection has no default Function for checking if a string is an element of it. This Function can be used to check if a collection contains a string (Just paste this Function somewhere in your code):

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

Now, this is how your code should look like:

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.