从外部链接重复提取时出现错误91

时间:2017-07-17 06:09:31

标签: excel-vba msxml msxml2 vba excel

我的功能从外部网站提取汇率。

我可以为特定日期提取单一费率。

当我有一个不同日期的列表时,我收到错误91,并将该功能复制粘贴到整个列表中。 (我告诉Excel为每个特定日期应用此功能。)

这是我的代码(xDoc对象创建方法的功劳归功于analystcave.com/vba-xml-working-xml-files /中的AnalystCave):

Public Function GetCurrToUZS(ByRef Curr As String, ByRef date_param As Date) As Currency        
    Dim xDoc As Object
    Dim xParent As Object
    Dim getRateChild As Object
    Dim corrDate As String

    On Error GoTo errorHandler:

    If Len(Curr) <> 3 Then
        MsgBox "Current identifier should be 3 letters in lenght", vbCritical + vbOKOnly _
            , "ERROR!"
        Exit Function
    End If
    'transforms 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")
    With xDoc
        .async = False
        .validateOnParse = False
        .Load "http://cbu.uz/ru/arkhiv-kursov-valyut/xml/" & Curr & "/" & corrDate & "/"
    End With

    'Get Document Elements
    Set xParent = xDoc.DocumentElement
    Set getRateChild = xParent.ChildNodes(0).ChildNodes(7)

    GetCurrToUZS = getRateChild.Text 'output of the function

    Set xDoc = Nothing 'terminates xDoc Object
    Exit Function

errorHandler:
    MsgBox Err.Number, vbCritical + vbOKOnly, "Critical Error!"
    Exit Function
End Function

作为错误的一个例子,我在Dropbox(https://www.dropbox.com/s/dg2j6o4xjr9v488/FX%20Rate%20Extraction%20Error%20%28stackoverflow%29.xlsx?dl=0)上创建了一个带有列表日期的小Excel文件。第一个是使用此功能完成的,应该可以轻松提取速率而不会出现任何错误。将公式复制粘贴到所有其他日期后,将发生错误91.

1 个答案:

答案 0 :(得分:0)

错误91表示未设置对象。

您最可能的赌注是,无法始终从您指定的网址中检索xDoc。如果我转到http://cbu.uz/ru/arkhiv-kursov-valyut/xml/usd/14.01.17(表单中的第3个日期),您将获得11.07.2017的XML。事实上,如果你转到http://cbu.uz/ru/arkhiv-kursov-valyut/xml,你会看到所有提供的记录都是针对特定日期的。

将错误处理放在无法抓取xDoc并随后无法设置xParentgetRateChild的情况下,它应该像魅力一样。