'How to save IF condition as Boolean Variable?

The logic on my code depends on the user who is running the macro.
e.g. if username is “abc” or “def” do something and if not do something other.
That why I use the same lengthy code of If conditions many times.
Is there any way to save IF condition as Boolean Variable ?
Appreciate for any useful comments and answers.

Option Explicit
Option Compare Text
 
Sub Run_Depends_on_Username()
     If UserName = "ABC" Or UserName = "DEF" Or UserName = "XYZ" Then
       'Code
     End If
End Sub

And this is the function to get username

Function UserName() As String
  UserName = Environ("username")
End Function


Solution 1:[1]

Generally, you can assign the result of a boolean expression directly to a variable, eg

Dim isAllowed as boolean
isAllowed = (UserName = "ABC" Or UserName = "DEF" Or UserName = "XYZ" )

' Use it:
if isAllowed Then

Alternative is to create a simple function

Function isAllowed() As Boolean
     isAllowed = (UserName = "ABC" Or UserName = "DEF" Or UserName = "XYZ")
End Function

Solution 2:[2]

Not only does it work, it is also a very good idea, as you can see in the following screenshot (the watch-window shows the current values of the boolean variables):

enter image description here

Hereby the source code:

Sub Run_Depends_on_Username()
Dim Username As String
Dim b_ABC, b_DEF, b_XYZ As Boolean

Username = "DEF"

b_ABC = (Username = "ABC")
b_DEF = (Username = "DEF")
b_XYZ = (Username = "XYZ")


     If b_ABC Or b_DEF Or b_XYZ Then
        Range("A1").Value = "Yes"
     End If
End Sub

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 FunThomas
Solution 2 Dominique