2016-09-26 380 views
1

我遇到了Shell.Application对象的Namespace方法依赖于调用子中没有变量声明而失败的情况。VBA:Shell.Application命名空间函数根据变量声明在调用子程序时失败

简化测试用例低于:

Function TestShellApplicationNamespace(folder) 

Dim oShell: Set oShell = CreateObject("Shell.Application") 
Dim oDir: Set oDir = oShell.Namespace(folder) 

Debug.Print TypeName(folder) 

If oDir Is Nothing Then 
    Debug.Print "oDir is Nothing" 
Else 
    Debug.Print "oDir is not Nothing" 
End If 

End Function 

这是由叫做:

Sub CallTestShellApplicationNamespace() 

Dim folder As String 

folder = "C:\" 

TestShellApplicationNamespace folder 

folder2 = "C:\" 

TestShellApplicationNamespace folder2 

End Sub 

结果我从运行该得到的是:

String 
oDir is Nothing 
String 
oDir is not Nothing 

我不确定无论这是VBA解释器中的错误还是我做错了什么。

编辑:提交此之后,也发现其是相关的以下的(虽然不完全相同)

Excel VBA Shell.Namespace returns Nothing

回答

2

Shell界面奇怪,它希望由值传递的参数,以便改变它的功能的原型于:

Function TestShellApplicationNamespace(ByVal folder As Variant) 

(或带有额外的括号调用)

TestShellApplicationNamespace (folder) 
ret = TestShellApplicationNamespace((folder)) 

您应该真正配置IDE以使其不会运行带有未声明变量的代码。