为excel2010创建等效的google doc电子表格函数importxml()函数

时间:2012-04-06 21:31:00

标签: xpath excel-vba vba excel

我在过去的谷歌电子表格中使用过,特别是他们的importxml()函数。我想知道是否有办法在VBA中构建一个函数(对于Excel 2010)(我不是很精通在VBA上创建函数),谷歌函数可以复制到excel 2010文件中运行吗? / p>

我找到了一些我认为可以使用的VBA代码,但我似乎无法运行它来给我想要的东西。

理想情况下,我想将一个单元格(在excel 2010中)放入以下函数并获取xpath内容。即:= importXML(“web url”,“xpath”)

非常感谢任何指导。

最佳

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

1 个答案:

答案 0 :(得分:1)

如果您是Windows用户,可以使用Neil Bosma's SEO tools来运行Xpath功能。