Excel VBA Set & Read System Environment Variables

System Environment Variables using VBA

These are some of the variables that are using by operating system.

The well known example is the “PATH” variable that has all the path for major software executable files and reference files.
This means that they Operating system will first search for a typed command or files in these paths.

If suppose this variable is not defined, then we have to type the complete path of each exe file in every program and command. Similar to this PATH, the other environment variables serve different purpose.

Now, we got some basic idea about environment variable.

Lets see how to read it using Excel vba code.

Excel VBA Code to Read System Environment Variables

For this purpose we can use the command VBA.Environ or VBA.Environ$.

Both serve the same purpose. We can either pass the index number of the Environment variable or its actual name.

Sub OT_Get_Environment_Variables()
     Dim strEnvironment As String, i As Double
     'Get Environment Variable String & Path
     For i = 1 To 255
        strEnvironment = Environ(i)
        ThisWorkbook.Sheets(1).Cells(i, 1) = strEnvironment
     'Get Environment Value using String
     MsgBox Environ("PATH")
 End Sub

All these variables can be seen directly using the command prompt itself. in Windwos + R (Run command) type cmd. This in open the command prompt.

Now type “set”  & press enter.

This will list all the system variables defined in your OS.

SET System Environment Variables using Excel VBA

when we are coding, we might want to set existing or create new environment variable for the program to work properly.

As far as I researched, no method does this perfectly. May be Microsoft has kept this as secure so that no program changes these settings accidentally.

If you are still looking for a good answer, please read these page. It has some good solid code.

  1. SET Environment variables
  2. Different methods & surprises in SET Environment experiments

This code snippet will set the new value to the mentioned Environment variable.

Leave a Reply