1

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

我找到了一些我认为可以使用的 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
4

1 回答 1

1

如果您是 Windows 用户,您可以使用Neil Bosma 的 SEO 工具来运行 Xpath 功能。

于 2013-02-05T12:03:31.813 回答