【问题标题】:VBA: How to wait until the excel download is complete?VBA:如何等到excel下载完成?
【发布时间】:2019-10-30 10:27:01
【问题描述】:

我有一个宏,它可以导航到一系列网页,从这些网页下载 Excel,然后将数据合并到打开的工作簿中。但是,我的代码失败了,因为它找不到新下载的工作簿。当我单步执行代码时,没有问题。大概我的代码继续运行,但由于新下载的工作簿尚未打开,它失败了。

我试图创建一个循环,等待下载的工作簿打开,但似乎在循环运行时工作簿无法打开。

如何在我的代码中“等待”直到工作簿打开并且我的代码可以继续? 任何意见表示赞赏,谢谢!

appIE.document.getElementById("_id3805:_id3806:0:_id4177").Click 'click website download button
Dim o As IUIAutomation
Dim e As IUIAutomationElement, download_check As IUIAutomationElement
Set o = New CUIAutomation
Dim h As LongLong
h = appIE.Hwnd
h = FindWindowEx(h, 0, "Frame Notification Bar", vbNullString)
If h = 0 Then Exit Sub
Set e = o.ElementFromHandle(ByVal h)
Dim iCnd As IUIAutomationCondition
Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Open")
Dim Button As IUIAutomationElement
Set Button = e.FindFirst(TreeScope_Subtree, iCnd)
Dim InvokePattern As IUIAutomationInvokePattern
Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)
InvokePattern.Invoke


Debug.Print "Download Successful, Click OK"

Application.Wait (Now + TimeValue("00:00:02"))
DoEvents
' This part searching active workbook
Dim xWBName As String
Dim GetBook As String
Dim xWb As Workbook

Do Until Application.Workbooks.Count > 1
'    'I am waiting for something to happen
    DoEvents
    Application.Wait (Now + TimeValue("00:00:01"))
    Sleep 1000
Loop

For Each xWb In Application.Workbooks
    'xWBName = xWb.Name 'xWBName & xWb.Name & vbCrLf
    DoEvents
    If InStr(xWb.Name, "Data") Then
     GetBook = xWb.Name
    End If
Next
DoEvents
'Activate the required workbook
**Set wb2 = Workbooks(GetBook)**

【问题讨论】:

  • 从您的代码中不清楚您是如何打开特定下载文件的,因为您不知道它的名称。此外,还不清楚为什么同时使用 application.wait 和 sleep() 。你应该使用其中任何一种。尝试提供详细信息可能有助于我们更好地理解问题。
  • 嗨,上面的代码是我用来点击,然后在触发 Internet Explorer 的“下载通知框架”时选择“打开”选项(我不知道正在打开的文件的名称)。我曾尝试在我的循环中使用:doevents、application.wait 和 sleep(),因为我希望其中一个会“释放”vba 进程并允许打开 excel,但这些方法都没有这种效果。似乎无论此循环如何,在宏运行时下载的 excel 都无法打开。该文件仅在我退出宏时打开。
  • 当您手动打开文件时,VBA 代码在文件被打开并分配给 VBA 代码中的任何对象之前将无法控制该文件。所以它看起来不是处理这个问题的正确方法。如果可能的话,您可以将您的代码分成 2 个子部分,并在需要时运行它们。通过这种方式,您无需等待该文件。您可以在文件下载并打开后运行其他子程序。
  • 一切都发生在 vba 中,包括打开文件。
  • 您说您正在单击打开选项来打开文件。这是手动操作。

标签: excel vba internet-explorer


【解决方案1】:

我认为您使用 sleep 和 doEvents 的方法是解决它的好方法。在打开下载的工作簿之前,检查您的睡眠循环(如果存在),然后退出循环。

If Dir(pathToFile) <> "" Then
    'File has been found
end if

编辑: 我没有看到您尝试打开文件的部分。 在您的情况下,事情发生的顺序是: 1.下载文件 2.等待循环检查文件是否已下载 3. 打开文件

睡眠循环可能如下所示:

'Download the file here

dim fileFound as boolean
while not fileFound
    sleep(1000)
    DoEvents
    If Dir(pathToFile) <> "" Then
        fileFound = true
    end if
wend

'Open the file here

【讨论】:

  • 嗨。目前,我的代码卡在了 sleep/doevents 循环中。似乎在代码循环时,excel无法打开下载。因此,我认为循环条件没有问题,就像我“等待”的方式一样。此外,我并不总是知道我正在下载的文件的确切名称
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-18
相关资源
最近更新 更多