2014-11-24 109 views
1

我試圖使用GET參數從HTTP鏈接打開XLS文件。如果您只是將鏈接複製並粘貼到您的網絡瀏覽器中,您將看到它的工作原理。如果我省略了GET參數,我可以用workbooks.open打開工作簿,但是它會打開錯誤的工作簿,因爲您需要GET參數來準確拉取我想要的內容。使用GET參數從URL打開Excel(XLS)文件

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 

感謝您的協助!

回答

2

我相信你不能直接從Excel中的URL打開文件,除非它是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名字變爲如GET請求

您可以選擇響應數據寫入文件時,任何你想要的文件名的 結果隨機做什麼。如果保留服務器發回的文件名很重要,那實際上很難。您必須查看響應頭的Content-Disposition字段,然後從中解析出文件名。

+0

謝謝你的回答,兩個問題,我在這行「Put #fno,responseData()」中得到一個語法錯誤,以及如果ViewstockScreener.xls名稱由於GET請求而變得隨機化,該怎麼辦。 – CodeCamper 2014-11-25 14:55:15

+0

非常感謝!字節在我的舌頭上被抓住了。請解釋爲什麼在Byte之後有一個(),並且請更正Put,最後recnumber需要像這樣'put #fno ,, responseData()',否則它會給我一個錯誤。一旦解決了這兩件事情,我會將其標記爲最佳答案。 – CodeCamper 2014-11-25 15:59:34