Can you set a Window's Environment variable in VB

K

Ken Soenen

Is there any way to set a Window's Environment variable from within Visual
Basic Code. I know I can read one via the VB Environ.

thanks,
ken
 
B

Bob Phillips

From a previous post.

That is exactly what we use it for, dev and prod.


What problem exactly are you getting with the SetEnvironmentVariable API? Is
it that trying to read it with Environ in the same NT/XP session does return
a value? If that is the case, I think this is because Excel seems to load
the environment variables at start-up, and Environ gets the values locally.
So any changes that you make are not reflected in Environ. And as
SetEnvironmentVariable only sets the variable for the current session, this
stymies you.


You can get around it though by using GetEnvironmentVariable to read it as
this will read any variables in the current session. This code snippet
should demonstrate it, GetEnvironmentVariable returns the newly set value,
Environ doesn't


Option Explicit


Private Declare Function GetEnvironmentVariable Lib "kernel32" _
Alias "GetEnvironmentVariableA" _
(ByVal lpName As String, _
ByVal lpBuffer As String, _
ByVal nSize As Long) As Long


Private Declare Function SetEnvironmentVariable Lib "kernel32" _
Alias "SetEnvironmentVariableA" _
(ByVal lpName As String, _
ByVal lpValue As String) As Long


Sub xx()
SetEnvironmentVariable "Rob", "Nuzie!"
MsgBox Environ("Rob")
MsgBox GetEnvironmentVar("Rob")
End Sub


Function GetEnvironmentVar(Name As String) As String
GetEnvironmentVar = String(255, 0)
GetEnvironmentVariable Name, GetEnvironmentVar, Len(GetEnvironmentVar)
GetEnvironmentVar = TrimNull(GetEnvironmentVar)
End Function


Private Function TrimNull(item As String)
Dim iPos As Long
iPos = InStr(item, vbNullChar)
TrimNull = IIf(iPos > 0, Left$(item, iPos - 1), item)
End Function


--
HTH

Bob Phillips

(remove nothere from email address if mailing direct)
 
K

Ken Soenen

Thanks Bob and Dave for the responses.
I downloaded SETX as suggested by Dave and it will set any EXISTING
variable. The SetEnvironmentVariable function suggested by Bob does the
same. The GetEnvironmentVariable function appears to get the variable if it
is a NEW variable(set by SetEnvironmentVariable) but not if it is an
EXISTING variable. Again, thanks for your responses. I'm a lot closer now
than I was before.

ken
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top