VBA(Excel)中的异步文件下载 [英] Asynchronous File Downloads from Within VBA (Excel)

查看:330
本文介绍了VBA(Excel)中的异步文件下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试过使用许多不同的技术,一个非常好的工作,但运行时仍然使用api调用绑定代码:

I've already tried using many different techniques with this... One that works pretty nicely but still ties up code when running is using the api call:

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

IF URLDownloadToFile(0, "URL", "FilePath", 0, 0) Then
End If

我还使用(成功)代码从内部编写vbscript Excel然后运行它wscript并等待回调。但是再一次,这并不是完全异步的,而且仍然绑定了一些代码。

I've also used (Successfully) code to write vbscript from within Excel and then running with it wscript and waiting for the callback. But again this isn't totally async and still ties up some of the code.

我希望将文件下载到事件驱动的类中,VBA代码可以在DoEvents的大循环中执行其他操作。当一个文件完成后,它可以触发一个标志,代码可以在等待另一个文件时处理该文件。

I'd like to have the files download in an event driven class and the VBA code can do other things in a big loop with "DoEvents". When one file is done it can trigger a flag and the code can process that file while waiting for another.

这是从Intranet网站拉出excel文件。如果这有帮助。

This is pulling excel files off of an Intranet site. If that helps.

由于我确定有人会问,除了VBA,我不能使用任何东西。这将在工作场所使用,90%的电脑是共享的。我非常怀疑他们会为了获得我的Visual Studio而付出代价。所以我必须与我的工作。

Since I'm sure someone will ask, I can't use anything but VBA. This is going to be used at the workplace and 90% of the computers are shared. I highly doubt they'll spring for the business expense of getting me Visual Studio either. So I have to work with what I have.

任何帮助将不胜感激。

推荐答案

您可以使用异步模式下的xmlhttp和类来处理其事件:

You can do this using xmlhttp in asynchronous mode and a class to handle its events:

http://www.dailydoseofexcel.com/archives/2006/10/09/async-xmlhttp-calls/

这里的代码是寻址responseText,但是你可以调整它来使用.responseBody。这是一个(同步)的例子:

The code there is addressing responseText, but you can adjust that to use .responseBody. Here's a (synchronous) example:

Sub FetchFile(sURL As String, sPath)
 Dim oXHTTP As Object
 Dim oStream As Object


    Set oXHTTP = CreateObject("MSXML2.XMLHTTP")
    Set oStream = CreateObject("ADODB.Stream")
    Application.StatusBar = "Fetching " & sURL & " as " & sPath
    oXHTTP.Open "GET", sURL, False
    oXHTTP.send
    With oStream
        .Type = 1 'adTypeBinary
        .Open
        .Write oXHTTP.responseBody
        .SaveToFile sPath, 2 'adSaveCreateOverWrite
        .Close
    End With
    Set oXHTTP = Nothing
    Set oStream = Nothing
    Application.StatusBar = False


End Sub

这篇关于VBA(Excel)中的异步文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆