2016-08-09 139 views
1

我正嘗試通過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 
+0

嘗試'xmlHTTP.responseText' – cyboashu

+0

之前打開流,你應該使用循環來檢查'xmlHTTP.ReadyState = 4' - 以'DoEvents' - 甚至短'Sleep'通話之後確保文檔已完全加載 – dbmitch

+0

@cyboashu,將.responseBody更改爲.responseText yeilds「參數的類型錯誤...」錯誤消息。 – Mateyobi

回答

1

嘗試通過身份驗證頭髮送密碼。看看是否有效。

Set xmlHTTP = New MSXML2.xmlHTTP 
    xmlHTTP.Open "GET", strURL, False 
    xmlHTTP.setRequestHeader "Authorization", "Basic " & EncodeBase64 
    xmlHTTP.Send 

'EncodeBase Function. Put your actual user name and password here. 
Private Function EncodeBase64() As String 
    Dim arrData() As Byte 
    arrData = StrConv("<<username>>" & ":" & "<<password>>", vbFromUnicode) 

    Set objXML = New MSXML2.DOMDocument 
    Set objNode = objXML.createElement("b64") 

    objNode.DataType = "bin.base64" 
    objNode.nodeTypedValue = arrData 
    EncodeBase64 = objNode.text 

    Set objNode = Nothing 
    Set objXML = Nothing 
End Function 
+0

'StrConv(「<>」&「:」&「<>」,vbFromUnicode)'yeilds error message'Error parsing'????????????'作爲bin.base64數據類型。我該怎麼辦? – Mateyobi

+0

<,把你用來登錄網站的用戶名。密碼相同。 – cyboashu

+0

我做了,我嘗試了,沒有<< >>。同樣的錯誤。我需要添加參考嗎? – Mateyobi