从外部链接重复提取时出现错误91
问题描述:
我的功能从外部网站提取汇率。从外部链接重复提取时出现错误91
我可以提取特定日期的单一费率。
当我列出不同日期时,出现错误91,并将该功能复制粘贴到整个列表中。 (我告诉Excel为每个特定日期应用此功能。)
这是我的代码(xDoc对象创建方法的功劳归于AnalystCave位于analystcave.com/vba-xml-working-xml-files/):
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错误。
答
错误91表示未设置对象。
您最可能的猜测是xDoc
不能总是从您指定的URL中检索。如果我去http://cbu.uz/ru/arkhiv-kursov-valyut/xml/usd/14.01.17
(工作表中的第3个日期),你会得到XML为11.07.2017
。事实上,如果您访问http://cbu.uz/ru/arkhiv-kursov-valyut/xml
,您会看到所有提供的记录都是针对该特定日期的。
将错误处理置于无法取得xDoc
,随后无法设置xParent
和getRateChild
,它应该像魅力一样工作。
@Chrotensie,谢谢你的评论。是的,如果我忽略日期并缩短网址,它仍然会检索费率,正如您所说的那样。问题在于它会一直检索最新的一个(并且11.07.2017是中央银行最新的一个)。为了使它检索任何以前的日期,我将需要使用原始链接。我不确定我是否真正理解了有关错误处理的建议(我不擅长XML;事实上,我只是VBA编程中的业余爱好者),并且我不确定这个建议是否适用,因为我继续使用原始网址。 –
@Chrotensie,另外,您继续获取11.07.2017而不是14.01.2017的XML的原因是该日期的格式应该是正确的。如果你注意到,我在代码'corrDate'中有一个特殊的代码行,然后在'xDoc.Load'中跟着一个正斜杠。 –