Celine N
Celine N

Reputation: 135

How to get the title of a website page in VBA?

Here is a piece of code I have been working on to print the title of a window.

Dim my_title2  as Variant
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
MsgBox ("The number of pages is: " & IE_count)

For x = 0 To (IE_count - 1)
    On Error Resume Next
    my_url = objShell.Windows(x).document.Location
    my_title = objShell.Windows(x).document.Title

    If my_title Like "F-Engine" & "*" Then
        Set ie = objShell.Windows(x)
        my_title2 = ie.document.Title
        'my_title2 = objShell.Windows(x).document.Title

        MsgBox ("The wanted title for the page should corrrespond. " & my_title2)
        Exit For
    Else
    End If
Next

I am having trouble printing the title of the window after Set ie = objShell.Windows(x).

When y_title2 = ie.document.title, the MsgBox displays:

"The wanted title for the page should correspond."

It prints nothing after this sentence. So the title assigned to "ie" is not being displayed.

If my_title2 = objShell.Windows(x).document.title, the MsgBox displays:

"The wanted title for the page should correspond. F-Engine"

Why am I not able to print the title of the page with the first declaration of my_title2?

I am doing this to verify if the page is being correctly picked up after a title "F-Engine" is found. To do so, I am trying to print the value of the title of the Internet Explorer window. It seems like nothing has been set and passed.

Upvotes: 1

Views: 1256

Answers (1)

Tim Williams
Tim Williams

Reputation: 166146

Not every object in objShell.Windows represents an IE page/tab - they might be instances of Windows Explorer. In those cases there is no document property to access.

You can test for this instead of using On Error Resume Next:

Dim w As Object, myUrl, myTitle, ie

For Each w In CreateObject("Shell.Application").Windows
    If w.Name = "Internet Explorer" Then
        myUrl = w.document.Location
        myTitle = w.document.Title

        Debug.Print myUrl, myTitle

        If myTitle Like "F-Engine*" Then
            Set ie = w
            Debug.Print "Found: " & myTitle
            Exit For
        End If
    End If
Next w

Upvotes: 2

Related Questions