user5857081
user5857081

Reputation:

how to make a for Loop in an array in vba

I have been try this over and over again but got the same output. I would like to make a loop in an array of strings but the code only visits the first value. This is my code I've tried:

name = Environ("username")
user1= Array("name.name1", "name.name2")
user2= Array("name1.name1", "name1.name2")

For i = 0 To Size ' I used Size coz I will add more names
    If name = user1(i) Then
        MsgBox "User1"
    ElseIf name = user2(i) Then
        MsgBox "User2"
    Else
        errorLog
    End If
Next

Thank you in advance for your help!

Upvotes: 1

Views: 280

Answers (2)

user5857081
user5857081

Reputation:

This is what I've done to solve my problem.

name = Environ("username")
Dim found as Boolean
found = false
user1= Array("name.name1", "name.name2")
user2= Array("name1.name1", "name1.name2")

'to check for user2
For i = 0 To UBound(user1)
    If name = user1(i) Then
        MsgBox "User1"
        found = true
    End If
Next
'to check for user2
For i = 0 To UBound(user2)
    If name = user2(i) Then
        MsgBox "User2"
        found = true
    End If
Next

'Else if the username is not on the list, I have added a Boolean found.
if found = false then 
    MsgBox "Unidentified Access!"
end If

Thank you so much for all your guidance!

Upvotes: 0

Bathsheba
Bathsheba

Reputation: 234875

Unless you've provided an explicit declaration and starting value for Size, when it's used in a for loop, it will assume a variant numeric type with a value 0.

So you get For i = 0 To 0: i.e. the loop will iterate once.

Writing Option Explicit at the top of your module helps reduce bugs like this.

If you want to get the size of an array, use LBound and UBound.

Upvotes: 1

Related Questions