我正在尝试使用GET参数从HTTP链接打开XLS文件。如果您只是将链接复制并粘贴到Web浏览器中,您将看到它的工作原理。如果我省略了GET参数,我可以用workbooks.open打开工作簿但是它会打开错误的工作簿,因为你需要GET参数来完全按照我想要的那样。
Dim myURL As String
Dim winHttpReq As Object
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
myURL = "http://www.otcmarkets.com/common/ViewStockScreener.xls?otcMarketTier=&otcMarketTierDesc=&otcMarketTierGroup=&otcMarketTierId=&otcMarketTierGroupDesc=&allTierGroups=true&securityType=CORP&securityTypeDesc=Corporate%20Bond&countryId=&locale=&countryDesc=&localeDesc=&allLocales=true&sicIndustryIdentifier="
winHttpReq.Open "GET", myURL, False
winHttpReq.Send
MsgBox Len(winHttpReq.responseBody)
result = winHttpReq.responseBody
Dim x As Workbooks
Set x = result
x(1).Open
感谢您的协助!
答案 0 :(得分:2)
我相信您无法直接从Excel中的网址打开文件,除非它是SharePoint网站。
我认为您使用WinHttpRequest处于正确的轨道上,但在打开文件之前,您需要将结果保存到本地磁盘上的文件中。
Dim myURL As String
Dim winHttpReq As Object
Dim responseData() As Byte
Dim fname As String
Dim fno As Integer
Set winHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
myURL = "http://www.otcmarkets.com/common/ViewStockScreener.xls?" & _
"otcMarketTier=&otcMarketTierDesc=&otcMarketTierGroup=&" & _
"otcMarketTierId=&otcMarketTierGroupDesc=&allTierGroups=true&" & _
"securityType=CORP&securityTypeDesc=Corporate%20Bond&countryId=&" & _
"locale=&countryDesc=&localeDesc=&allLocales=true&sicIndustryIdentifier="
winHttpReq.Open "GET", myURL, False
winHttpReq.Send
responseData = winHttpReq.responseBody
fname = CurDur & "\ViewStockScreener.xls"
fno = FreeFile
Open fname For Binary As #fno
Put #fno, 1, responseData
Close #fno
Workbooks.Open fname
responseData之后的()将其声明为可变长度字节数组。首先将responseBody复制到原始字节数组中是必要的,因为将responseBody直接写入二进制文件会破坏数据(可能是某些字符编码问题)。
如果ViewstockScreener.xls名称随机化为a,该怎么办? GET请求的结果
您可以在将响应数据写入文件时选择所需的任何文件名。如果保留服务器发回的文件名很重要,那实际上有点困难。您必须查看响应标头的Content-Disposition字段并从那里解析出文件名。