The environmental variables are a dynamic-named values that can affect the way running processes will behave on a computer.
With other words, if you want to see them in your PC, simply open the command prompt and write the nice word Set and press Enter. This is how the first few look like:
These could be quite useful to be accessed in VBA as well. To be honest, there are very few of them that could actually be used in some real-life application, but it is good to know how to call them. The one I have used in VBA are the UserName one some variables, related to the default file paths.
This simple loop would print you the first 64 variables. If you have more, simply increase the counter:
1 2 3 4 5 6 |
Public Sub EnvironmentalVariables() Dim i As Long For i = 1 To 64 Debug.Print i; vbTab; Environ(i) Next i End Sub |
If you want to use the environmenta variables in a code, you have two options. Either call them with their index or by their key. The calling by the key would return only the value:
In a simple VBA code, the usage would be like this:
1 2 3 |
Public Sub WriteUserName() ThisWorkbook.Worksheets(1).Range("A1:A5") = Environ("Username") End Sub |
That’s all 🙂