Visual Basic Code of the Week (COTW)
Issue #88
Online Version at (paid subscribers only)
All content and source code is Copyright (c) 1999 by C&D Programming Corp. No part of this issue can be reprinted or distributed in any manner without express written permission of C&D Programming Corp. Word, Excel and Visual Basic are trademarks of Microsoft Corp.


Have a request for a topic in Code of the Week? Email us at

In this Issue

Token substitution using environment variables.



This module contains a single routine that does a substitution of environment variables in the data passed to it. It is very useful for processing command lines in which the user wants to use data that is stored in the environment (such as a username). It can also be used in any custom configuration or scripting files your application might use.

An environment variable is usually set in the AUTOEXEC.BAT (or any other batch file) or a network login script. The DOS command to set an environment variable is SET. An example would be SET USER=david.

If you have any questions about using this class, let us know at


Public Function ParseEnvVar(ByVal sData As String) As String

This routine will take the data passed in sData and search for any embedded environment variables. As it finds each environment variable it will substitute the value for the environment variable into the string. Once it processes all environment variables it will scan the string for an "escaped" delimiter (two delimiters next to each other) and replace them with a single delimiter character.


The processed string if successful. It will raise an error if something "bad" happens.

Sample Usage

Below is an example of how this function works. It assumes there is an environment variable called USER that is set to JOHN.

Debug.Print ParseEnvVar("The username is %user%.")

Source Code

To see the source code for this issue you must be a subscriber to Code of the Week. If you are a subscriber the source code is available at the following address:

This document is available on the web

Paid subscribers can view this issue in HTML format. There is no additional source or information in the HTML formatted document. It just looks a little better since we have included some HTML formatting. Just point your browser to link at the top of this document.

Other links

Contact Information

C&D Programming Corp.
PO Box 20128
Floral Park, NY 11002-0128
Phone or Fax: (212) 504-7945