Excel VBA从IE 11下载栏另存为

问题描述:

我有以下代码可以从网络上下载文件,但是我必须手动执行另存为.

I have the following code to download a file from the web, but I have to manually do a Save As.

  Dim Filename As String
  Dim ieApp As Object
  Dim URL As String

    URL = Range("All_Quad_URL")
    Filename = "C:\Historic_Weather_Data\Precipitation\" & Range("File_Name").Value

    Set ieApp = CreateObject("InternetExplorer.Application")
    ieApp.Visible = True
    ieApp.Navigate URL

      While ieApp.Busy Or ieApp.ReadyState <> 45
        DoEvents
      Wend

    ieApp.Quit

    Set ieApp = Nothing

我想自动执行另存为.我没有运气就尝试了以下方法:

I would like to automate Save As. I have tried the following with no luck:

控制IE11";您要打开/保存吗?VBA中的对话窗口按钮

我仍然看到带有打开/保存选项的查看下载-Internet浏览"对话框.我将 FindWindowEX 更改为 h = FindWindowEx(h,0,查看下载-Internet Explorer",vbNullString)

I still get the "View Downloads - Internet Explore" dialog box with the open/save options. I changed the FindWindowEX to h = FindWindowEx(h, 0, "View Downloads - Internet Explorer", vbNullString)

另存为"的文件名和位置必须为

The file name and location for the Save As needs to be

Filename = "C:\Historic_Weather_Data\Precipitation\" & Range("File_Name").Value

我也得到

运行时错误"-2147467259(80004005)":对象'IWebBrowser 2'的方法'忙'失败"

Run-time error "-2147467259 (80004005)': Method 'Busy' of object 'IWebBrowser 2' failed"

调试到 ieApp.Busy 行中的

.

感谢您的帮助.

不幸的是,IE不允许您设置保存下载的路径.我已经搜索了几个小时,直到找到答案.它将保存到您保存下载内容的最后一个位置.

Unfortunately IE doesn't let you set the path to save a download. I've searched this for hours until I found the answer. It will save to the last location you saved a download.

但是,我有一些好消息.单击下载按钮后,放置以下代码,该代码将为您工作.您还需要添加适当的库引用.

However, I have some good news. place the below code after you click the download button, and it should work for you. You'll also need to add the appropriate library references.

如果您想要保存另存为的完整代码,则可以找到它

if you want the full code for save as, you can find it Here

'wait for save as window to appear
Dim o As IUIAutomation
Dim h As LongPtr
Set o = New CUIAutomation
h = 0
Do Until h > 0
    'h = ie.hWnd
    h = FindWindow("#32770", "Internet Explorer")
Loop

'find and click save as button
Dim e As IUIAutomationElement
Dim iCnd As IUIAutomationCondition
Dim Button As IUIAutomationElement
Set e = o.ElementFromHandle(ByVal h)
Set Button = Nothing
Do Until Not Button Is Nothing
    Set iCnd = o.CreatePropertyCondition(UIA_NamePropertyId, "Save as")
    Set Button = e.FindFirst(TreeScope_Subtree, iCnd)
Loop

Dim InvokePattern As IUIAutomationInvokePattern
Set InvokePattern = Button.GetCurrentPattern(UIA_InvokePatternId)
InvokePattern.Invoke