连接字符串中的Windows环境变量

时间:2015-06-05 13:24:25

标签: excel vba odbc

如何在Excel工作表连接字符串中使用环境变量,获取错误,ODBC Excel驱动程序登录失败...不是有效路径

1 个答案:

答案 0 :(得分:0)

如果提供程序错误,那么它不会扩展字符串,您需要手动执行,在分配之前通过函数运行字符串。

在一个模块中:

Private Declare Function ExpandEnvironmentStrings Lib "kernel32" Alias "ExpandEnvironmentStringsA" (ByVal lpSrc As String, ByVal lpDst As String, ByVal nSize As Long) As Long

Public Function ExpandEnv(str As String) As String
    Dim size As Long
    size = ExpandEnvironmentStrings(str, ExpandEnv, size)
    ExpandEnv = Space$(size)
    size = ExpandEnvironmentStrings(str, ExpandEnv, size)
    ExpandEnv = Left$(ExpandEnv, size - 1)
End Function

有关

?ExpandEnv("aaa %temp% bbb %username% ccc") 
aaa C:\NULL bbb AlexK ccc