构建VBA UDF以从站点检索数据的最佳方法

时间:2015-03-19 04:51:03

标签: excel vba excel-vba

我需要构建一个Excel VBA用户定义函数,该函数从这样的网页中检索数据:

https://www.comdinheiro.com.br/Clientes/ServerToExcel/S2E_TESTANDO001.php?func1=retorno&func2=retorno(01/01/2011,16/03/2015,ptaxc,todos)

我知道我可以为每个函数的调用创建一个查询,但这会导致工作表上的查询过多。我也可以打开一个IE并“读取”html脚本来获取数据,但这需要花费很多时间。那么我错过了解决这个问题的其他可能方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

不确定这是否是最佳方法,但您可以使用MSXML2.XMLHTTP对象来请求该网站。

示例:

enter image description here

B2中的公式是=getResult(A2,B2)

UDF getResult是:

Public Function getResult(dFromDate As Date, dToDate As Date) As Double

 Dim sFromdate As String, sToDate As String
 sFromdate = WorksheetFunction.Text(dFromDate, "dd/mm/yyyy")
 sToDate = WorksheetFunction.Text(dToDate, "dd/mm/yyyy")

 Dim sURL As String, sArguments As String, sRequest As String

 sURL = "https://www.comdinheiro.com.br/Clientes/ServerToExcel/S2E_TESTANDO001.php"
 sArguments = "?func1=retorno&func2=retorno%28" & sFromdate & "," & sToDate & ",ptaxc,todos%29"
 sRequest = sURL & sArguments

 Dim httpObject As Object
 Set httpObject = CreateObject("MSXML2.XMLHTTP")
 httpObject.Open "GET", sRequest, False
 httpObject.send

 Dim sGetResult As String
 sGetResult = httpObject.responseText
 sGetResult = Replace(sGetResult, ".", Application.DecimalSeparator)

 getResult = CDbl(sGetResult)

End Function