0

我正在尝试使用 VBA 检查特定文件夹是否打开。我找到了这段代码:

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

但是我收到一个错误,即对象不支持此属性或方法。

有任何想法吗?

4

1 回答 1

1

感谢它也帮助我的代码......我已经检查过 Wnd.Document.Folder.Self.Path 不适用于所有 Window 对象,例如 IE,这就是为什么它会给你一个错误消息,我有通过首先检查窗口是否是 Windows 资源管理器窗口来完成。代码如下。

注意: Wnd.Document.Folder.Self.Path为您提供完整路径字符串,因此您可能希望将其与strFolder.

如果要将其与OpenFold变量进行比较,则可能要使用

Wnd.LocationName = OpenFold

最终代码:

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
于 2013-06-13T21:41:58.563 回答