简体   繁体   中英

check if a folder is open (vba)

I am trying to check whether a specific folder is open or not using VBA . I have found this code:

Sub test1()
Dim OpenFold As Variant
Dim oShell As Object
Dim Wnd As Object
Dim strFolder

OpenFold = "mysubfolder"
strFolder = "U:\myfolder\" & OpenFold
Set oShell = CreateObject("Shell.Application")

For Each Wnd In oShell.Windows
If Wnd.Document.Folder.Self.Path = OpenFold Then 'this is where it gives me the error
Exit Sub ' Folder is open - exit this Sub
End If
Next Wnd
Application.ThisWorkbook.FollowHyperlink Address:=strFolder, NewWindow:=True
End Sub

But i am getting an error that the object is not supporting this property or method.

Any ideas?

Thanks for the code it also helped me... I have checked that the Wnd.Document.Folder.Self.Path does not apply to all Window object, for example IE, that is why it will give you an error message, I have done it by checking first if the windows is a Windows Explorer window. Code below.

Notes: Wnd.Document.Folder.Self.Path gives you full path string so you might want to compare it with strFolder .

If you want to compare it to OpenFold variable you might want to use

Wnd.LocationName = OpenFold

Final Code:

Sub test1()
        Dim OpenFold As Variant
        Dim oShell As Object
        Dim Wnd As Object
        Dim strFolder

        OpenFold = "mysubfolder"
        strFolder = "U:\myfolder\" & OpenFold
        Set oShell = CreateObject("Shell.Application")

        For Each Wnd In oShell.Windows
            If Wnd.Name = "Windows Explorer" Then
               If Wnd.Document.Folder.Self.Path = strFolder Then Exit Sub 
            End If
        Next Wnd
        Application.ThisWorkbook.FollowHyperlink Address:=strFolder, NewWindow:=True
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM