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

问题描述 投票:0回答:1

我正在编写一个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
excel vba downloading-website-files
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.