2013-07-26 85 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在内部开发,这是我们的解决方案。希望这有助于其他寻找信息!

相关问题