Michael McCarthy Michael McCarthy - 3 years ago 150
HTML Question

Pull element from website by ID with Excel / VBA

I'm trying to retrieve values by element ID from a website using VBA and add them to my excel table. The website URL's are indicated in column A. Column B and C are for my retrieved values.

URL example
Element ID name: "youtube-user-page-country"

Excel Pic

Bellow is my poor attempt:

Sub getCountry()

Dim IE As New InternetExplorer
IE.Visible = False

IE.navigate Worksheets("Sheet1").Range(A3).Value
Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE

Dim Doc As HTMLDocument
Set Doc = IE.document

Dim getCountry As String

getCountry = Trim(Doc.getElementsByTagName("youtube-user-page-country").innerText)

Worksheets("Sheet1").Range(B31).Value = getCountry

End Sub


Any help would be appreciated!

Answer Source

I think I get what you are after. There were a few issues:

  1. You want to use getElementByID.
  2. Naming a string getCountry and the SubRoutine getCountry containing it is not a good idea. You can do it, but don't.
  3. Always fully qualify your sheet references so you know what workbook and sheet you are working with

Here's the revised code, I have it working on my end.

Sub getCountry()
    Dim IE      As Object: Set IE = CreateObject("InternetExplorer.Application")
    Dim ws      As Worksheet: Set ws = ThisWorkbook.Sheets("Sheet1")
    Dim Country As String

    With IE
        .Visible = False
        .navigate ws.Range("A3").Value

        Do
            DoEvents
        Loop Until .readyState = 4

    End With

    Country = Trim$(IE.document.getElementByID("youtube-user-page-country").innerText)
    ws.Range("B31").Value2 = Country
    IE.Quit
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download