How do I download a file using VBA (without Internet Explorer)

后端 未结 4 2195
难免孤独
难免孤独 2020-11-22 07:57

I need to download a CSV file from a website using VBA in Excel. The server also needed to authenticate me since it was data from a survey service.

I found a lot of

4条回答
  •  再見小時候
    2020-11-22 08:44

    This solution is based from this website: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

    It is slightly modified to overwrite existing file and to pass along login credentials.

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

提交回复
热议问题