控制IE11“是否要打开/保存” VBA

时间:2019-07-04 19:03:10

标签: vba

我在VBA上编写的代码有问题。我基本上是使用vba打开一个网站,输入信息,然后单击一个下载按钮,该按钮将下载一个csv,然后可以将其复制并放置到我的excel文件中。我确实设法完成所有工作,直至单击“下载”按钮。当我这样做时,将显示IE11的“对话”窗口,询问我是否要保存或打开文件。我不知道如何解决此问题以及如何单击打开或保存。对于Controlling IE11 "Do you want to Open/Save" dialogue window buttons in VBA中的相同问题,我已经尝试了解决方案中提到的所有内容,但是即使使用了此解决方案,代码也可以运行,但是什么也不做。

我尝试使用UIAutomation,但未成功。我使用了Controlling IE11 "Do you want to Open/Save" dialogue window buttons in VBA中提供的解决方案。我也尝试过使用Sendkeys,但是我不完全确定如何将重点放在Internet Explorer上,以便使sendkeys发挥应有的作用。

代码实际上非常简单

Sub GetHTMLDocument()

Dim ie As New SHDocVw.InternetExplorer
Dim HTMLDoc As HTMLDocument
Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim HTMLButton As MSHTML.IHTMLElement


ie.Visible = True
ie.Navigate "this is where i put the website"

Do While ie.ReadyState <> READYSTATE_COMPLETE
Loop

Set HTMLDoc = ie.Document
Set HTMLInput = HTMLDoc.getElementById("Search")
HTMLInput.Value = "Hello"
Set HTMLInput = HTMLDoc.getElementById("downloadCSV")
HTMLInput.Click


End Sub

不幸的是,我无法提供该网站,也无法使用公共网站,之后我得到了打开或保存在Internet Explorer上的消息

1 个答案:

答案 0 :(得分:0)

可能的VBA interaction with internet explorer副本

尽管对于这个特定问题,答案可能更清楚。

1)将其添加到模块顶部-它创建了一个函数,该函数可让您提供任何窗口焦点。我不知道细节。

Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long

2)修改此代码以尝试使用SendKeys

        'give IE focus to prepare for SendKeys
            ' IE.HWND = the handle of the Windows Internet Explorer main window.
                Dim HWNDSrc As Long
                HWNDSrc = IE.HWND
                SetForegroundWindow HWNDSrc

        'Make sure IE is not busy
            Do While IE.Busy
                Application.Wait DateAdd("s", 1, Now)
            Loop

        'send Alt-S to save
            Application.SendKeys "%{S}"

        'Make sure IE is not busy
             Do While IE.Busy
                 Application.Wait DateAdd("s", 1, Now)
             Loop