Excel VBA从IE 11下载栏另存为

时间:2019-05-09 15:41:54

标签: excel vba

我有以下代码可以从网络上下载文件,但是我必须手动执行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

我想自动化Save As。我没有运气就尝试了以下方法:

Controlling IE11 "Do you want to Open/Save" dialogue window buttons in VBA

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

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

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

我也得到

  

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

调试到While ieApp.Busy行。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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

但是,我有一些好消息。单击下载按钮后,放置以下代码,它应该对您有用。您还需要添加适当的库引用。

编辑:如果您想要保存另存为的完整代码,则可以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