Replace a variable Environ in vba

883 views Asked by At

Please, I had already create à variable Environ("MYXLSPATH")

Dim vr As String
vr = "SETX MYXLSPATH """ & ThisWorkbook.FullName & """"
Call Shell(vr)

And now, I want to replace the content of this variable by: "NAME"

Dim vr As String
Environ.RemoveItem ("MYXLSPATH")
vr = "SETX MYXLSPATH "" NAME """
Call Shell(vr)

But, It doesn't work, can you help me please ?

2

There are 2 answers

0
Robson On

The second set of code should be:

Dim vr As String
vr = "SETX MYXLSPATH ""NAME"""
Call Shell(vr)

I've made two changes:

  1. Removed the Environ.RemoveItem line. It's not needed and seems to be problematic.
  2. Removed the space either side of NAME. So this means the environment variable is set to NAME and not  NAME 

End result:

enter image description here

0
HackSlash On

Instead of running a CMD.EXE command you can call in to the Shell object to get to the environment variables directly. To replace, just call the set again.

Here are procedures to set and get:

Option Explicit

'@Description("Set environment variable value. Defaults to user space. System space requires elevated process to modify.")
Public Sub EnvironSetItem(ByVal environVariable As String, ByVal newValue As String, Optional ByVal strType As String = "User")
    With CreateObject("WScript.Shell").Environment(strType)
        .Item(environVariable) = newValue
    End With
End Sub

'@Description("Get environment variable value. Defaults to userspace.")
Public Function EnvironGetItem(ByVal environVariable As String, Optional ByVal strType As String = "User") As String
    With CreateObject("WScript.Shell").Environment(strType)
        EnvironGetItem = .Item(environVariable)
    End With
End Function