Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading