Excel VBA Shell.Namespace returns Nothing

后端 未结 2 499
[愿得一人]
[愿得一人] 2021-01-25 08:22

I\'m trying to extract a .CAB file using Excel VBA, but I\'m getting the following error:

Run-time error \'91\': Object variable or With block variable no

相关标签:
2条回答
  • 2021-01-25 09:02

    Your parameters must be submitted as Variant, not 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

    0 讨论(0)
  • 2021-01-25 09:11

    Tim's answer is correct. I found an alternative, as well:

    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
    

    When you place an object in parentheses in VBA, it returns the default value of the object. Apparently, objShell.Namespace can't handle a pointer. It can only handle a string literal. Changing the signature to the following also works if you're passing in Strings:

    Private Function DeCab(ByVal vSource, ByVal vDest) As Long
    
    0 讨论(0)
提交回复
热议问题