Michael McCarthy Michael McCarthy - 3 years ago 136
HTML Question

How do I pull value from external website by Element ID with Excel / VBA?

I'm trying to retrieve values from external websites by element ID 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
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

The code isn't working showing problems with object definition.
Could anyone give me tips on where I'm going wrong?

I've been a macro recorder user and the switch has quite a steep learning curve :-)

Thanks for any help !

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

        Loop Until .readyState = 4

    End With

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