使用VB自动化IE“将目标另存为”

时间:2008-12-13 16:29:13

标签: excel internet-explorer save-as

我正在尝试使用excel VB宏从受会员密码保护的网站下载excel文件。我正在使用“InternetExplorer”对象打开浏览器窗口,登录并浏览到正确的页面,然后在页面中扫描我想要的链接。使用Workbooks.Open(URLstring)不起作用,因为未记录Excel。它打开了要求登录的html页面,而不是实际的文件。

我的偏好是使用VB宏在正确的链接上自动右键单击“在Internet Explorer中保存目标为”事件,但我不确切知道如何执行此操作。

2 个答案:

答案 0 :(得分:1)

使用Internet Explorer API实际上没有办法实现这一点。如果它只是一个一次性的脚本,你可以证明使用SendKeys给自己辩护。

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
...
Sub YourMacro()
    ... Navigate IE to the correct document, and get it to pop 
    up the "Save As" dialog ...

    Set sh = CreateObject("WScript.Shell")
    sh.AppActivate "File Download"
    sh.SendKeys "S"
    Sleep 100
    sh.SendKeys "C:\Path\filename.ext{ENTER}"
End Sub

WScript.Shell documentation

答案 1 :(得分:0)

如果您知道要下载的文件的URL,则可以使用此例程:

Sub HTTPDownloadFile(ByVal URL As String, ByVal LocalFileName As String)
    Dim http As Object ' Inet
    Dim Contents() As Byte

    Set http = New Inet
    Set http = CreateObject("InetCtls.Inet")
    With http
        .protocol = icHTTP
        .URL = URL
        Contents() = .OpenURL(.URL, icByteArray)
    End With
    Set http = Nothing

    Open LocalFileName For Binary Access Write As #1
    Put #1, , Contents()
    Close #1
End Sub