如何使用VBA下载文件(没有Internet Explorer)

我需要在Excel中使用VBA从网站下载CSV文件。 服务器还需要validation我的身份,因为这是来自调查服务的数据。

我发现很多使用由VBA控制的Internet Explorer的例子。 然而,这大多是缓慢的解决scheme,大部分也是令人费解的。

更新: 一段时间后,我发现了一个在Excel中使用Microsoft.XMLHTTP对象的漂亮的解决scheme。 我想分享下面的解决scheme,以备将来参考。

此解决scheme基于此网站: http : //social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save- CSV从-url

它稍微修改为覆盖现有文件并传递login凭据。

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 
 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 

资源

我find了上面的时候寻找FTP下载用户名和地址在URL中。 用户提供信息然后进行呼叫。

这是有帮助的,因为我们的组织有卡巴斯基AV阻止active http://FTP.exe,但不是networking连接。; 我们无法与ftp.exe一起开发,这是我们的解决scheme。 希望这有助于其他寻找信息!