【问题标题】:Excel Custom Function to Retrieve XML Data用于检索 XML 数据的 Excel 自定义函数
【发布时间】:2016-01-27 08:02:17
【问题描述】:

我想创建一个自定义函数来检索以 XML URL 链接形式提供的特定数据。这是我第一次在 Excel 中处理 XML,更不用说 VBA,并且正在努力解决它。

我已经能够编写一个程序(本地货币汇率检索),只需按下一个自定义按钮即可运行,该按钮运行以下代码:

Sub FX_Retrieve()
    Dim FX As String
    Dim CustomDate As String

    FX = Range("FX")
    CustomDate = Range("CustomDate")

    Application.ScreenUpdating = False

    ActiveSheet.Unprotect 
    Rows(2).Clear
    ActiveWorkbook.XmlImport URL:= _
        "http://www.cbu.uz/section/rates/widget/xml/" & FX & "/" & CustomDate, ImportMap:= _
        Nothing, Overwrite:=True, Destination:=Range("C2")
    Range("D:D").EntireColumn.AutoFit
    Rows(2).HorizontalAlignment = xlCenter
    Columns(6).ClearContents
    ActiveSheet.Protect 

    Application.ScreenUpdating = True
End Sub

以防万一,XML 输出如下所示: 2015-12-29 美元 2809.98 1 因此,需要在我的代码中进行一些格式化。

在单次调用外汇汇率的情况下,该程序没有问题! 现在,我想更进一步并创建一个函数。这就是我提出几个问题的地方:

  1. 我需要从 xml 输出中提取特定的子节点(速率),如下所示:

'

<response>
<date_act>2015-12-29</date_act>
<symbol>USD</symbol>
<rate>2809.98</rate>
<size>1</size>
</response>

我已经找到了类似的东西(如这里:Excel VBA getting specific node from XML),但我无法在我的情况下应用它。

  1. 就我所见,函数的创建不允许采用与我的过程中相同的方法。

任何帮助将不胜感激!

【问题讨论】:

    标签: xml vba excel


    【解决方案1】:

    感谢@Dick Kusleika 运营的 AnalystCave.com 网站,我能够根据我的问题调整那里提供的关于“使用 XML 文件”主题的信息,并成功解决了它。以防万一有人遇到同样的问题,这是我的代码(我只是希望它在编程上高效):

    Public Function GetCurrToUZS(ByRef Curr As String, ByRef date_param As Date) As Currency
        Dim XDoc As Object
        Dim lists
        Dim getThirdChild
        Dim corrDate As String
    
        If Len(Curr) <> 3 Then
            MsgBox "Currency name must be 3 letters long!", vbCritical + vbOKOnly _
                , "VARIABLE ERROR!"
            Exit Function
        End If
        'corrects the entered date to the required format of "YYYY-MM-DD"
        corrDate = Year(date_param) & "-" & Month(date_param) & "-" & Day(date_param)
    
        Set XDoc = CreateObject("MSXML2.DOMDocument")
        XDoc.async = False: XDoc.validateOnParse = False
        XDoc.Load "http://www.cbu.uz/section/rates/widget/xml/" & Curr & "/" & corrDate
    
        'Get Document Elements
        Set lists = XDoc.DocumentElement
        Set getThirdChild = lists.ChildNodes(2)
    
        GetCurrToUZS = getThirdChild.Text 'output of the function
    
        Set XDoc = Nothing 'terminates xDoc Object
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-13
      • 2016-01-30
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      相关资源
      最近更新 更多