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
 

Some videos you may like

Excel Facts

Why are there 1,048,576 rows in Excel?
The Excel team increased the size of the grid in 2007. There are 2^20 rows and 2^14 columns for a total of 17 billion cells.

VoG

Legend
Joined
Jun 19, 2002
Messages
63,650
Try

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

rickincanada

Board Regular
Joined
Aug 31, 2010
Messages
61
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.
 

VoG

Legend
Joined
Jun 19, 2002
Messages
63,650
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
 

Watch MrExcel Video

Forum statistics

Threads
1,127,035
Messages
5,622,332
Members
415,894
Latest member
silverhaze

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
Top