Excel VBA Shell.Namespace返回Nothing

我正在尝试使用Excel VBA提取.CAB文件,但出现以下错误:

运行时错误“91”:

对象variables或未设置块variables

当我忘记使用Set with Object时,我通常会得到这个,但是我已经检查过了。

我能find的所有例子都是这个主题的变体:

 Private Function DeCab(vSource, vDest) As Long Dim objShell, objFileSource, objFileDest As Object Set objShell = CreateObject("Shell.Application") Set objFileSource = objShell.Namespace(vSource) Set objFileDest = objShell.Namespace(vDest) Call objFileDest.MoveHere(objFileSource.Items, 4 Or 16) 'Fails here Decab = objFileDest.Items.Count End Function 

Set行上没有失败,但是它将objFileSourceobjFileDest设置为Nothing即使我已经确认了vSourcevDest存在。

为了确认它与.CAB文件无关,我也试过了,没有设置objFileSource并在设置objFileSource检查它的值。 它仍然Nothing返回。 为什么会这样? 我在Windows 7,64位上运行Office 2010。

您的参数必须提交为变体,而不是string

 Sub Tester() Dim src, dest '<< works 'Dim src As String, dest As String '<< gives the error you see src = "D:\temp\test.zip" dest = "D:\temp\unzip" DeCab src, dest End Sub 

https://msdn.microsoft.com/en-us/library/windows/desktop/bb774085(v=vs.85).aspx

Tim的回答是正确的。 我也find了一个替代scheme:

 Private Function DeCab(vSource, vDest) As Long Dim objShell, objFileSource, objFileDest As Object Set objShell = CreateObject("Shell.Application") Set objFileSource = objShell.Namespace((vSource)) '<-extra parentheses Set objFileDest = objShell.Namespace((vDest)) '<-extra parentheses Call objFileDest.MoveHere(objFileSource.Items, 4 Or 16) 'Fails here Decab = objFileDest.Items.Count End Function 

在VBA中将对象放在括号中时,它将返回对象的默认值。 显然, objShell.Namespace不能处理一个指针。 它只能处理一个string文字。 如果您传入string,则将签名更改为以下内容也适用:

 Private Function DeCab(ByVal vSource, ByVal vDest) As Long