Reputation: 329
Is it possible for the child process to change or pass back an environment variable to the parent process?
For example:
I have a batch file that runs a sequence of access databases. Once the database has run through its queries i want to pass a value back to the batch file using VBA - but i can't seem to get this to work.
I can read the parent variable by using the getEnvironmentVariable
functions but the setEnvironmentVariable
doesn't seems to work.
Upvotes: 0
Views: 616
Reputation: 130839
Your vba will have its own copy of the batch environment that called it. You can set a value in the local copy, but it will disappear once vba returns control back to your batch script. So the answer is no, you cannot do what you want directly.
What you want to do is a common need. One solution is to write the values to a temporary file and then have the parent batch script read the values in and delete the temp file.
You can avoid a temporary file if your vba can write to stdout - I assume you can, but I'm not sure. Your batch script could call your database via FOR /F and process the stdout output. There are a lot of options for how FOR /F parses the output.
The general syntax is:
for /f "options" %%A in ('yourCommand') do (REM process values using %%A)
Type HELP FOR
or FOR /?
from the command prompt to get full help on the FOR command.
Upvotes: 2
Reputation: 13088
You can execute a cmd command from vba, so to set an environment variable you could use:
Dim cmd_str
cmd_str = "setx env_var_name env_var_value"
Call Shell(cmd_str, vbNormalFocus)
Note that this will create / set the environment variable for the current user, a /M parameter can be added to make this system wide, but cmd has to be run as an adminsitrator for this to work.
The vbNormalFocus option will allow the command prompt to appear and then disappear after a moment, if you don't want to see it use vbHide instead.
Upvotes: 0