使用EXCEL vba下载文件时出现问题

时间:2019-03-15 00:56:24

标签: excel vba downloading-website-files

我正在编写一个android应用程序,我需要一个相当大的数据库。我正在使用Excel和vba构造此数据库。我已经在谷歌上搜索了很多,为了下载一个网页(将数据提取到我的数据库中),我想出了下面的代码。但这不起作用。它始终返回downloadResult = 2148270085。任何有好的建议的人吗?我使用的是64位系统,并使用EXCEL2013 64位版本。

Option Explicit
Declare PtrSafe Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA" ( _
        ByVal pcaller As LongPtr, _
        ByVal szURL As String, _
        ByVal szFileName As String, _
        ByVal dwReserved As LongPtr, _
        ByVal lpfnCB As LongPtr) As LongPtr

Sub DownloadFileButton_Clicked()
    Dim fileURL As String
    Dim fileName As String
    Dim downloadResult As LongPtr
    fileURL = "http://www.wordreference.com/definicion/estar"
    fileName = Application.ThisWorkbook.Path + "\" + "estar.htm"
    downloadResult = URLDownloadToFile(0, fileURL, fileName, 0, 0)
    If downloadResult = 0 then
        Debug.Print "Download started"
    Else
        Debug.Print "Download not started, error code: " & downloadResult
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

好吧,我最终使用了httpRequest而不是URLDownloadFile,但也无法使其正常工作。经过数小时的测试,我终于发现这是我的防火墙阻止了该请求。在尝试向防火墙添加例外之后,我最终在使用代码时关闭了防火墙。希望这对某人有帮助。我很确定URLDownloadFile也将卡在防火墙中。

Sub DownloadFileButton_Clicked3(language As String, verb As String) ' Fr Es It
    Const WinHttpRequestOption_EnableRedirects = 6
    Dim httpRequest As Object
    Dim URL As String, myString As String
    Set httpRequest = CreateObject("WinHttp.WinHttpRequest.5.1")
    URL = "http://www.wordreference.com/conj/" + language + "Verbs.aspx?v=" + verb
    httpRequest.Option(WinHttpRequestOption_EnableRedirects) = True
    httpRequest.Open "GET", URL, False
    'httpRequest.setRequestHeader "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"
    'httpRequest.SetTimeouts  'connection with the server could not be established
    httpRequest.Send
    httpRequest.WaitForResponse
    Debug.Print Len(httpRequest.ResponseText)
    myString = httpRequest.ResponseText
    Dim fileName As String
    fileName = Application.ThisWorkbook.Path + "\" + verb + ".htm"
    Open fileName For Output As #1
    Print #1, myString
    Close #1
    Set httpRequest = Nothing
End Sub