HTTPSresource的Excel VBA URLDownloadToFile错误

时间:2016-01-21 12:07:16

标签: excel vba file excel-vba download

我尝试使用VBA从Excel中的服务器下载文件。这在使用HTTP时工作正常,但不能使用HTTPS工作。

我可以在Internet Explorer中访问这两个地址(HTTP / HTTPS)。如果我将URLDownloadToFile与HTTP地址一起使用,则会下载该文件。

使用HTTPSadress时,我会收到返回码-2146697211。也许这是证书问题?

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

    Dim Ret As Long

    Sub DownloadCode()
        Dim strURL As String
        Dim strPath As String
        strURL = "https:/url.de/module.bas"
        strPath = Environ("TEMP") & "\Module.bas"
        Ret = URLDownloadToFile(0, strURL, strPath, 0, 0)

        If Ret = 0 Then
    '        MsgBox "File successfully downloaded"
        Else
            MsgBox "Returncode:" & Ret & " Unable to download Code`enter code here`."
        End If
    End Sub

1 个答案:

答案 0 :(得分:1)

如果其他人有这个问题:我的问题是,服务器需要客户端证书。通常https调用都不是VB的问题。对于自签名证书,必须从文件系统或Windows证书库发送证书。

Dim oStream As Object
 Dim myURL As String

 myURL = "URL"

 Dim WinHttpReq As Object
 Set WinHttpReq = CreateObject("WinHttp.WinHttpRequest.5.1")
 WinHttpReq.Option(4) = 13056 ' Ignore SSL Errors

 WinHttpReq.Open "GET", myURL, False

 ' Grab Cert from Windows Cert Store
'WinHttpReq.SetClientCertificate "CURRENT_USER\Root\CERTI"

 WinHttpReq.setRequestHeader "Accept", "*/*"
 WinHttpReq.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
 WinHttpReq.setRequestHeader "Proxy-Connection", "Keep-Alive"
 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 Environ("TEMP") & "\File", 2
  oStream.Close
  Else
        MsgBox "Returncode:" & WinHttpReq.Status & " Unable to download  Code."
 End If