下载到文件和readystate = 4

时间:2016-12-01 16:22:29

标签: vba

我正在尝试编写代码来下载一个非常大的文件,根据带宽,可能需要30分钟才能下载。我现在有一个非常基本的脚本,通常在文件完全下载之前终止。有没有办法使用readystate或类似的东西,让VBA允许整个文件下载后继续下载?

以下是代码:

Sub Download()
    Dim strURL As String
    Dim strPath As String

    '~~> URL of the Path
    strURL = "http://www.aeronav.faa.gov/upload_313-/terminal/DDTPPE_201612.zip"
    '~~> Destination for the file
    strPath = "c:\Users\username\Desktop\WebTest\database.zip"

    Ret = URLDownloadToFile(0, strURL, strPath, 0, 0)

End Sub

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以将您的网址放在单元格中并运行下面的脚本。

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

Sub DownloadFilefromWeb()
    Dim strSavePath As String
    Dim URL As String, ext As String
    Dim buf, ret As Long
    URL = Worksheets("Sheet1").Range("A2").Value
    buf = Split(URL, ".")
    ext = buf(UBound(buf))
    strSavePath = "C:\Users\your_path_here\" & "DownloadedFile." & ext
    ret = URLDownloadToFile(0, URL, strSavePath, 0, 0)
    If ret = 0 Then
        MsgBox "Download has been succeed!"
    Else
        MsgBox "Error"
    End If
End Sub

enter image description here

如果您想循环遍历包含许多网址的范围,那就是这样。如果您只想下载一个,请尝试这种方式。

Declare Function URLDownloadToFileA Lib "urlmon" _
(ByVal pCaller As Long, _
ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) As Long

Sub ExampleDownload()
Dim IExpl As Object
Set IExpl = CreateObject("InternetExplorer.Application")
With IExpl
.Navigate "http://www.bom.mu/?id=80277" 'You need to change this for a variable and loop
Do Until .Readystate = 4: Loop ' Allow page to load
'Code below to find correct href link in page based on text
For Each lnk In IExpl.Application.Document.Links
If lnk.outertext = "Click Here to Open or Right Click to Download." Then Exit For
Debug.Print lnk.outertext
Next
End With
SuccessfulDownload = URLDownloadToFileA(0, lnk.href, "C:\myfilename.zip", 0, 0)
Set IExpl = Nothing
End Sub

答案 1 :(得分:0)

或者,尝试R,这是快速的!要使您的数据下载和解压缩,您需要设置mode="wb"

download.file("...",temp, mode="wb") 
unzip(temp, "gbr_Country_en_csv_v2.csv") 
dd <- read.table("gbr_Country_en_csv_v2.csv", sep=",",skip=2, header=T)

然后,只需从Excel工具中读取CSV。