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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用EXCEL vba下载文件时出现问题相关的知识,希望对你有一定的参考价值。

我正在编写一个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
答案

好吧,我最终得到了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

以上是关于使用EXCEL vba下载文件时出现问题的主要内容,如果未能解决你的问题,请参考以下文章

将公式插入单元格 VBA Excel 时出现运行时错误 1004

Selenium VBA Excel - 单击 iframe 中的链接时出现问题

从 Excel VBA 运行工作参数化 Access SQL 查询 (INSERT INTO) 时出现“需要对象”错误

为啥从 Word doc 调用宏时出现错误 1004,而不是从 Excel 调用?

尝试在 Excel VBA 中设置 RefersToRange 属性时出现问题

excel用vba时出现运行错误6-溢出,请帮忙看下我的程序是否有问题