3

I'm writing a script to open documents using the default program via the Windows shell based on this SO answer:

Dim Shex As Object
Set Shex = CreateObject("Shell.Application")
tgtfile = "C:\Nax\dud.txt"
Shex.Open (tgtfile)

I notice the instance of Shell.Application never gets closed. In my code, I Set Shex = Nothing, but is that enough? If I create a Word or Outlook instance, for example, I would need to close it with .Quit before setting the variable to nothing. There's nothing obviously analogous going on here.

I set a reference to Microsoft Shell Controls and Automation to explore the Shell object, but couldn't find any methods for the .Application or .Parent properties, let alone one that looked like .Quit.

Am I missing something obvious? Does the garbage collector somehow also get rid of the instance? Is it something specific to the shell object itself?

braX
  • 11,506
  • 5
  • 20
  • 33
PKB
  • 321
  • 1
  • 11
  • I don't think you really instance an application; the object created in VBA just allows you the same access you'd get from a Shell GUI to the same file/folder heirarchy, so once the object is set to nothing it's gone. – jamheadart May 27 '20 at 06:30
  • 1
    Or to put it another way, you're only instancing a class which gives you an interface to access this, that and the other, but not an actual stand-alone application. – jamheadart May 27 '20 at 06:35
  • 1
    You may find this discussion helpful: https://stackoverflow.com/questions/42164719/how-to-destroy-an-object . One suggestion is to limit the scope of the object's existence by framing it within a "with" statement. – MYZ May 27 '20 at 07:29

1 Answers1

0

Thinking about it, I'm pretty sure @jamheadart is right and I'm just instancing a VBA class rather than creating an application class in Windows.

To be sure, though, I'm taking @Mert Y's suggestion of using a context manager to limit scope.

Final code:

With CreateObject("Shell.Application")
    .Open (strPath)
End With
PKB
  • 321
  • 1
  • 11