Visual Basic Code of the Week (COTW)
http://www.codeoftheweek.com
Issue #88
Online Version at http://www.codeoftheweek.com/membersonly/bi/0088.html (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.

Requests

Have a request for a topic in Code of the Week? Email us at request@codeoftheweek.com

In this Issue

Token substitution using environment variables.

Requirements

basParseEnvVar

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 questions@codeoftheweek.com

Functions

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.

Returns

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

Just paste this code into any module and change the name of the module to basParseEnvVar. Be sure to also include the code that appeared in issue 9 if you want it to support the feature to replace a double delimiter (see comments near the end of the ParseEnvVar routine.

'----------------------------------------------------------------------
'
'   Routine Name:   ParseEnvVar
'   Written By:     C&D Programming Corp.
'   Create Date:    03/30/99
'   Copyright:      Copyright 1999 by C&D Programming Corp.  Source
'                   code may not be reproduced except for use in a
'                   compiled executable.  All rights reserved.  If
'                   you would like to reprint any or all of this
'                   code please email us at info@codeoftheweek.com
'
'   Purpose:        Allow substitution of any environment strings into
'                   the data passed as sData.
'
'----------------------------------------------------------------------

Option Explicit

Public Function ParseEnvVar(ByVal sData As String) As String
    Dim lPos As Long
    Dim lEndPos As Long
    Dim sToken As String
    Dim sEnvVar As String
    Const DELIM = "%"

    On Error GoTo Handler
    lPos = InStr(sData, DELIM)
    While lPos <> 0
        lEndPos = InStr(lPos + 1, sData, DELIM)
        If lEndPos <> 0 Then
            If lEndPos - 1 = lPos Then ' we have a double delimiter so ignore it
                lPos = InStr(lEndPos + 1, sData, DELIM) ' force it to skip these and search again
            Else
                ' pull out the token between the delimiters
                sToken = Mid(sData, lPos + 1, lEndPos - lPos - 1)
                ' retrieve the token value from the environment (you could also
                ' retrieve the value from someplace else let a database, ini file
                ' or registry).
                sEnvVar = Environ$(sToken)

                ' put together the new string with the token replaced with the value
                ' determined from the previous line.
                sData = Left(sData, lPos - 1) & sEnvVar & Mid$(sData, lEndPos + 1)

                ' search whole string again, allows nested environment variables
                lPos = InStr(1, sData, DELIM)
            End If
        Else
            ' no more delimiters were found so skip outta here.
            lPos = 0
        End If
    Wend

    ' now just replace the %% with %
    ' to perform the replacement of double percent signs you will need
    ' issue number 9 - Search/Replace strings
    ' This is not required to parse the environment strings, it just
    ' provides the extra feature of being able to change the double
    ' percent signs to single ones.
    sData = ReplaceChars(sData, DELIM & DELIM, DELIM)
    ParseEnvVar = sData
    Exit Function

Handler:
    ParseEnvVar = ""
    Err.Raise Err.Number, "ParseEnvVar", Err.Description
End Function

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
Email: info@codeoftheweek.com
Web: http://www.codeoftheweek.com