2013-07-26 84 views
29

我需要使用Excel中的VBA從網站下載CSV文件。由於服務器是調查服務的數據,服務器還需要對我進行身份驗證。如何使用VBA下載文件(無需Internet Explorer)

我發現了很多使用由VBA控制的Internet Explorer的例子。然而,這大多是緩慢的解決方案,大部分也是令人費解的。

更新: 一段時間,我發現使用Microsoft.XMLHTTP對象在Excel中一個漂亮的解決方案後。我想分享下面的解決方案以備將來參考。

回答

43

該方案基於此網站: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

它略作修改,以覆蓋現有文件,並沿着登錄憑據傳遞。

Sub DownloadFile() 

Dim myURL As String 
myURL = "https://YourWebSite.com/?your_query_parameters" 

Dim WinHttpReq As Object 
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP") 
WinHttpReq.Open "GET", myURL, False, "username", "password" 
WinHttpReq.send 

myURL = WinHttpReq.responseBody 
If WinHttpReq.Status = 200 Then 
    Set oStream = CreateObject("ADODB.Stream") 
    oStream.Open 
    oStream.Type = 1 
    oStream.Write WinHttpReq.responseBody 
    oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite 
    oStream.Close 
End If 

End Sub 
+0

謝謝 - 非常酷。我唯一的問題是,那麼任何獲得文件的VBA的人都有你的密碼。任何提示,以解決或以某種方式加密它?再次感謝! – rryanp

+2

沒問題:)你是對的,在你的代碼中存儲密碼不是好習慣。在Ruby中我總是使用環境變量,你可能在VBA中做類似的事情。在Excel中,您可以加密文件,以便用戶無法使用您的代碼。我從來沒有試過這個,但試試這個鏈接:http://www.vbaexpress.com/forum/showthread.php?914-how-to-encrypt-vba-code-on-the-fly –

+3

什麼是「myURL = ... responseBody「(在If之前)for?似乎不必要... –

6
Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" _ 
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, _ 
ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long 

Sub Example() 
    DownloadFile$ = "someFile.ext" 'here the name with extension 
    URL$ = "http://some.web.address/" & DownloadFile 'Here is the web address 
    LocalFilename$ = "C:\Some\Path" & DownloadFile !OR! CurrentProject.Path & "\" & DownloadFile 'here the drive and download directory 
    MsgBox "Download Status : " & URLDownloadToFile(0, URL, LocalFilename, 0, 0) = 0 
End Sub 

Source

我希望從FTP下載,在URL的用戶名和地址時,發現以上。用戶提供信息然後進行呼叫。

這很有幫助,因爲我們的組織擁有卡巴斯基AV,它阻止了FTP.exe,但不包括網絡連接。我們無法使用ftp.exe在內部開發,這是我們的解決方案。希望這有助於其他尋找信息!

相關問題