jtchase08
jtchase08

Reputation: 660

Or in If-Then-Else statement in VBA

I have this bit of code:

If TempVars!CurrentUsername <> "user1" Then
...
Else
...
End If

What I'd like to do is add a few more users to the first if statement. I've tried the following:

If TempVars!CurrentUsername <> "user1" or "user2" Then

and

If Not TempVars!CurrentUsername Like "user1" or "user2" Then

and

If TempVars!CurrentUsername Not Like "user1" or "user2" Then

All three attempts yield the same

Run-time error '13':
Type mismatch

error.

I'm new to VBA, so this could be something simple that I'm simply over-looking. Or is my syntax completely wrong?

Upvotes: 1

Views: 127

Answers (3)

Darren Bartrup-Cook
Darren Bartrup-Cook

Reputation: 19837

Maybe use SELECT CASE instead?

 Select Case TempVars!CurrentUsername

        Case "user1", "user2"
            'Code for these users.

        Case "user3"
            'Code for these other users.

        Case Else
            'Code for any other users not covered.

    End Select

Upvotes: 2

Ron Deijkers
Ron Deijkers

Reputation: 3101

You should repeat the variable TempVars!CurrentUsername in your statement.

If TempVars!CurrentUsername <> "user1" And TempVars!CurrentUsername <> "user2" Then

It uses And because of the <> symbols. To make it work with Or as in your first example you would actually write something like (pseudocode):

NOT (X = "1" OR X = "2")

But that can also be rewritten to:

X <> "1" AND X <> "2"

Upvotes: 4

Jack Frost
Jack Frost

Reputation: 21

I believe you need to use syntax like:

If TempVars!CurrentUsername <> "user1" AND TempVars!CurrentUsername <> "user2" Then

Upvotes: 2

Related Questions