我正嘗試通過Excel VBA從IBM Cognos下載文件。該腳本將執行,但我只有一個9KB的Excel文件不會打開。我如何完成這項工作?
這裏是我的代碼:通過VBA下載Excel文件
Sub ado_stream()
'add a reference to Microsoft XML v6 and MS ActiveX Data Objects
'via Tools/References
'This assumes the workbook is saved already, and that you want the file in the same folder
Dim fileStream As ADODB.Stream
Dim xmlHTTP As MSXML2.xmlHTTP
Dim strURL As String
strURL = "http://foo.bar"
Set xmlHTTP = New MSXML2.xmlHTTP
xmlHTTP.Open "GET", strURL, False, "username", "password"
xmlHTTP.Send
If xmlHTTP.status <> 200 Then
MsgBox "File not found"
GoTo exitsub
End If
Set fileStream = New ADODB.Stream
With fileStream
.Open
.Type = adTypeBinary
.Write xmlHTTP.responseBody
.Position = 0
.SaveToFile "C:\Users\myname\Downloads\Test.xlsx"
.Close
End With
exitsub:
Set fileStream = Nothing
Set xmlHTTP = Nothing
End Sub
嘗試'xmlHTTP.responseText' – cyboashu
之前打開流,你應該使用循環來檢查'xmlHTTP.ReadyState = 4' - 以'DoEvents' - 甚至短'Sleep'通話之後確保文檔已完全加載 – dbmitch
@cyboashu,將.responseBody更改爲.responseText yeilds「參數的類型錯誤...」錯誤消息。 – Mateyobi