Takes an input string containing environment variables %temp%, %username%, etc) and returns the same string with those variables expanded (e.g., resolved to their final value)
Ex:
?ExpandString("C:\users\%username%\desktop")
C:\users\Jack\desktop
' ExpandEnvironmentVariableString
' http://www.utteraccess.com/wiki/ExpandEnvironmentVariableString
' Code courtesy of UtterAccess Wiki
' Licensed under Creative Commons License
' http://creativecommons.org/licenses/by-sa/3.0/
'
' You are free to use this code in any application,
' provided this notice is left unchanged.
'
' rev date brief descripton
' 1.0 2018-06-24
'
Public Function ExpandString(StringIn As String) As String
'Returns the input string with all environment variables expanded
On Error GoTo Error_Proc
'===========================
Dim ret As String
Dim s As String, v As Variant, i As Integer
Dim EnvironVars As String
'===========================
ret = StringIn
v = Split(StringIn, "%")
For i = 0 To UBound(v)
'if we're on an odd number, it'll be the start of a variable
If i Mod 2 = 1 Then
EnvironVars = EnvironVars & ";" & CStr(v(i))
End If
Next i
If EnvironVars = "" Then
GoTo Exit_Proc
End If
'trim leading delimiter
EnvironVars = Mid(EnvironVars, 2)
v = Split(EnvironVars, ";")
For i = 0 To UBound(v)
ret = Replace(ret, "%" & CStr(v(i)) & "%", Environ(CStr(v(i))))
Next i
'===========================
Exit_Proc:
On Error GoTo 0
ExpandString = ret
Exit Function
Error_Proc:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure ExpandString of Function Environment"
Resume Exit_Proc
Resume
End Function