I have used in the past google spreadsheets, an in particular their importxml() function. I would like to know if there is a way to build a function in VBA (for Excel 2010) (i'm not very savvy creating functions on VBA) whereby the google function could be replicated to be run within an excel 2010 file?
I have found some VBA code that I thought it could be used but I cannot seem to run it to give me what I want.
Ideally, I would like to put on a cell (within excel 2010) the following function and get the xpath content. ie: =importXML("web url","xpath")
Any guidance will be greatly appreciated.
Best Paco
Option Explicit
Public Sub WaitBrowserQuiet(objIE As InternetExplorer)
Do While objIE.Busy Or objIE.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
End Sub
Public Function getXPathElement(sXPath As String, objElement As HTMLBaseElement) As HTMLBaseElement
Dim sXPathArray() As String
Dim sNodeName As String
Dim sNodeNameIndex As String
Dim sRestOfXPath As String
Dim lNodeIndex As Long
Dim lCount As Long
' Split the xpath statement
sXPathArray = Split(sXPath, "/")
sNodeNameIndex = sXPathArray(1)
If Not InStr(sNodeNameIndex, "[") > 0 Then
sNodeName = sNodeNameIndex
lNodeIndex = 1
Else
sXPathArray = Split(sNodeNameIndex, "[")
sNodeName = sXPathArray(0)
lNodeIndex = CLng(Left(sXPathArray(1), Len(sXPathArray(1)) - 1))
End If
sRestOfXPath = Right(sXPath, Len(sXPath) - (Len(sNodeNameIndex) + 1))
Set getXPathElement = Nothing
For lCount = 0 To objElement.childNodes().Length - 1
If UCase(objElement.childNodes().Item(lCount).nodeName) = UCase(sNodeName) Then
If lNodeIndex = 1 Then
If sRestOfXPath = "" Then
Set getXPathElement = objElement.childNodes().Item(lCount)
Else
Set getXPathElement = getXPathElement(sRestOfXPath, objElement.childNodes().Item(lCount))
End If
End If
lNodeIndex = lNodeIndex - 1
End If
Next lCount
End Function
Private Sub cmdGetQuote_Click()
Dim ie As InternetExplorer
Dim elem As HTMLBaseElement
Dim url As String
url = "http://www.bloomberg.com/quote/MXIBTIIE:IND"
Set ie = New InternetExplorer
ie.Visible = True
ie.Navigate url
WaitBrowserQuiet ie
Set elem = getXPathElement("//span[@class=' price']", ie.Document)
Range("A1").Value = elem.innerText
Set ie = Nothing
End Sub