VBA objShell.windows.title 找不到标题

VBA objShell.windows.title not finding title

我运行这个功能用两个IE浏览器打开。 IE_count 找到六个 objects,但在 objShell 的 for 循环中没有找到任何标题 (my_title)。他们都是return一个空字符串。

知道为什么会这样吗?相关代码如下:

' code below adapted from ron's answer here: 
Function SecondBrowserSearchForAndClick(ElementID As String, searchFor As String)
    Dim objShell
    Set objShell = CreateObject("Shell.Application")
    
    Dim IE_count As Integer
    IE_count = objShell.Windows.Count
    
    Dim x As Integer
    For x = 0 To (IE_count - 1)
        On Error Resume Next    ' sometimes more web pages are counted than are open
        
        Dim my_url As String
        my_url = objShell.Windows(x).document.Location
        
        Dim my_title As String
        my_title = objShell.Windows(x).document.Title
        
        If my_title Like "*Select Process*" Then 'compare to find if the desired web page is already open
            Dim tagColl_TR As Object
            Set tagColl_TR = objShell.Windows(x).document.getElementById(ElementID).contentDocument.getElementsByTagName("tr")
            Dim f
            While f < tagColl_TR.Length
                If tagColl_TR(f).Children.Length = 5 Then
                    If tagColl_TR(f).Children(3).Children(0).innerText Like "*" & searchFor & "*" Then
                        tagColl_TR(f).Children(1).Children(0).Children(1).Focus
                        tagColl_TR(f).Children(1).Children(0).Children(1).Click
                        Exit Function
                    End If
                End If
                f = f + 1
            Wend
        End If
    Next
End Function

如有任何帮助,我们将不胜感激。

将“按标题查找文档”功能放在自己的函数中更容易:

Sub Tester()
    Dim doc As Object
    
    Set doc = IEDocumentByTitle("Google")
    If Not doc Is Nothing Then
        Debug.Print "Found window at: " & doc.Location
        'work on doc here
    End If
End Sub

'Return an open IE document based on its Title property
Function IEDocumentByTitle(title As String)
    Dim w As Object, ttl As String
    For Each w In CreateObject("Shell.Application").Windows
        If w.Application.Name = "Internet Explorer" Then 'filter out Windows Explorer
            ttl = ""
            On Error Resume Next
            ttl = w.document.title
            On Error GoTo 0
            If ttl Like title Then
                Set IEDocumentByTitle = w.document
                Exit Function
            End If
        End If
    Next w
End Function

这对我来说很好。

顺便说一句 shell Windows collection 除了 IE windows/tabs.

还包括 Windows Explorer 实例

此外,您确实应该尽快取消 On Error Resume Next ,否则它会悄悄吞噬您代码中的所有错误,可能会导致意外结果。