Expand / un-expand environment variable strings
- John
- 3 minutes ago
- 2 min read
This post is one of a series providing implementation examples of Windows API Functions, Types, Enums and Consts using VBA. The code in this post can be used as-is, however, if you regularly (or even just occasionally) work with Windows API declarations in VBA, you may want to see the posts Automatically add Windows API declaration(s) and Using 'F1' to view Windows API web pages which explain some of the functionality that can be added to the VBE by VBE_Extras.
An un-expanded environment variable string is one of these things ...
%userprofile%
%username%
%computername%
%programfiles%
%homedrive%
... there are many more of them. You often see them in registry keys or returned from various calls to the Windows API or WMI etc. They represent values that are specific to a device or a user. You can read more about them on this Environment Variables page.
They can be expanded to their full value using the ExpandEnvironmentStrings Windows API Function and, for file/folder paths, can be unexpanded (contracted?) using the PathUnExpandEnvStrings Windows API Function. Note that these two Functions both operate for the current user (which 99.99% of the time is what you want) ... but you should be aware that every user on a device has their own environment variables which, obviously, have user-specific values ... see the Environment Variables link above for more details.
Here's the declarations of the two Windows API Functions along with helper methods to make using them simpler from other VBA code:
And here's some demo code to use / test those helper functions:
Obviously, what is printed out by the "expands to" and "unexpands to" lines depends on your environment variables.