Using IF/ElseIF to Set VBA Variable

rickincanada

Board Regular
Joined
Aug 31, 2010
Messages
61
I'm struggling to Set a variable based on an if statement. What I want is to set the variable User = Environ("USERNAME") if the Environ("USERNAME") does not equal userB or userC. If the Environ("USERNAME") does equal userB or userC then I want User = userA. Here's what I have however I'm getting an "Else without If" error. Any help you can provide would be greatly appreciated!

Dim User As String

If Environ("USERNAME") = "userB" Then User = "userA"
If Environ("USERNAME") = "userC" Then User = "userA"
ElseIf Environ("USERNAME") <> "UserB" Or Environ("USERNAME") <> "userC" Then User = Environ("USERNAME")
End If
 

Excel Facts

Best way to learn Power Query?
Read M is for (Data) Monkey book by Ken Puls and Miguel Escobar. It is the complete guide to Power Query.
Try

Code:
Dim User As String
If Environ("USERNAME") = "userB" Or Environ("USERNAME") = "userC" Then
    User = "userA"
Else
    User = Environ("USERNAME")
End If
 
Upvote 0
Thanks VoG...

One other question, as this is used on many different servers I can never be certain that case will always be correct on the "userB" and "UserC" so I'm wondering if I should be converting the case? In some cases it could be "USERC" or "UserC", etc, etc.
 
Upvote 0
Try this

Code:
Dim User As String
If UCase(Environ("USERNAME")) = "USERB" Or UCase(Environ("USERNAME")) = "USERC" Then
    User = "userA"
Else
    User = Environ("USERNAME")
End If
 
Upvote 0

Forum statistics

Threads
1,224,527
Messages
6,179,348
Members
452,907
Latest member
Roland Deschain

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top