Visual Basic 6 function "EnvironString"

Go back

Below you'll find the source for the Visual Basic 6 function EnvironString.

Attribute VB_Name = "modEnvironString"
' These functions are downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

''
' Gets the value of an environment key
' @param    String  keyname     The environment keyname
' @return   String              The value
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function EnvironGetKey(ByVal keyname As String) As String
    If Left(keyname, 1) = "%" And Right(keyname, 1) = "%" Then keyname = Mid(keyname, 2, Len(keyname) - 2)
    Dim i As Integer, equalpos As Integer
    i = 1
    Do While Environ(i) <> ""
        equalpos = InStr(Environ(i), "=")
        If equalpos > 0 Then
            If LCase(Left(Environ(i), equalpos - 1)) = LCase(keyname) Then
                EnvironGetKey = Right(Environ(i), Len(Environ(i)) - equalpos)
                Exit Function
            End If
        End If
        i = i + 1
    Loop
End Function

''
' Replaces %name% values with it's environment values
' @param    String  text        The text with %name% keys
' @return   String              The full version
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function EnvironString(ByVal text As String) As String
    Dim percentpos1 As Integer, percentpos2 As Integer
    Dim s1 As String, s2 As String
    Do
        percentpos1 = InStr(text, "%")
        If percentpos1 = 0 Then Exit Do
        percentpos2 = InStr(percentpos1 + 1, text, "%")
        If percentpos2 = 0 Then Exit Do
        s1 = Mid(text, percentpos1, percentpos2 - percentpos1 + 1)
        s2 = EnvironGetKey(s1)
        If s2 = "" Then Exit Do
        text = Replace(text, s1, s2)
    Loop While True
    EnvironString = text
End Function