Add new Environment Variable Name and Value

419 views Asked by At

I wanted to set a new Environment Variables Name "Sample" and Value "E:\Sample" onto user variables not on system variables.

How do I do this using VBA excel?

Thank you and kind regards,

2

There are 2 answers

1
vague guy On
Sub addEnvironVariables()

    Dim WSS: Set WSS = CreateObject("WScript.Shell")
    Set System = WSS.Environment("User")
    System.Item("Sample") = System.Item("Sample") & ";C:\Sample"

End Sub

Found it on youtube

0
Ericksan Pimentel On

For me the following steps worked (Excel 2019)

To create/set an environment variable:

Dim objUserEnvVars As Object
Set objUserEnvVars = CreateObject("WScript.Shell").Environment("User")
objUserEnvVars.item("Test") = "Blah"

To read the environment variable:

Dim objUserEnvVars As Object
Dim strVar As String
Set objUserEnvVars = CreateObject("WScript.Shell").Environment("User")
strVar = objUserEnvVars.item("Test")
MsgBox strVar

My reference is: https://eileenslounge.com/viewtopic.php?t=4857

You can use on .Environment() to save your variable:

  • "System": Returns the system environment variables.
  • "User": Returns the current user's environment variables.
  • "Process": Returns the environment variables of the current process.
  • "Volatile": Returns the current user's volatile environment variables.