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

后端 未结 4 2163
难免孤独
难免孤独 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:53

    A modified version of above to make it more dynamic.

    Public Function DownloadFileB(ByVal URL As String, ByVal DownloadPath As String, ByRef Username As String, ByRef Password, Optional Overwrite As Boolean = True) As Boolean
        On Error GoTo Failed
    
        Dim WinHttpReq          As Object: Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
    
        WinHttpReq.Open "GET", URL, False, Username, Password
        WinHttpReq.send
    
        If WinHttpReq.Status = 200 Then
            Dim oStream         As Object: Set oStream = CreateObject("ADODB.Stream")
            oStream.Open
            oStream.Type = 1
            oStream.Write WinHttpReq.responseBody
            oStream.SaveToFile DownloadPath, Abs(CInt(Overwrite)) + 1
            oStream.Close
            DownloadFileB = Len(Dir(DownloadPath)) > 0
            Exit Function
        End If
    
    Failed:
        DownloadFileB = False
    End Function
    

提交回复
热议问题