The Environ function in VBA allows you to get the value of an environment variable from the operating system. Environment variables contain information about the system environment, such as the user’s name, the system directory, and the path to temporary files.
Basic Syntax
VBA
Replace “VARIABLE_NAME” with the actual name of the environment variable you would like to retrieve.
Here are the steps and an example demonstrating how to use the Environ function:
Dim envVariable As String
envVariable = Environ("VARIABLE_NAME")
- Open Microsoft Excel.
- Press Alt + F11 to open the Visual Basic for Applications editor (VBA editor).
- Insert a new module by clicking Insert > Module from the menu.
- In the new module, create a new subroutine or function where you want to use Environ.
Environ to get the username and the path to the user’s Temp folder
VBA
To run the above code:
Sub ShowEnvironmentVariables()
Dim userName As String
Dim tempPath As String
' Get the username of the current user
userName = Environ("USERNAME")
' Get the path to the temporary folder
tempPath = Environ("TEMP") ' or Environ("TMP")
' Display the results in message boxes
MsgBox "Current user is: " & userName
MsgBox "Path to TEMP folder is: " & tempPath
End Sub
- Ensure you are in the VBA editor and that the new module is selected.
- Place the cursor inside ShowEnvironmentVariables subroutine.
- Press F5 to execute the code.