vba从url下载excel工作簿并保存到c盘?

时间:2014-11-13 11:28:47

标签: excel vba

我正在尝试下载excel工作簿并将其保存到本地计算机上的用户c驱动器。出于某种原因,我在以下行的上下文中不允许出现错误操作:

oStream.Write WinHttpReq.ResponseBody

有人可以告诉我哪里出错了吗?

感谢

Dim myURL As String
myURL = "http://eu.storagemadeeasy.com/files/357eb15ab28bade4da58c149506d00d8.xls"

    Dim WinHttpReq As Object
    Set WinHttpReq = CreateObject("MSXML2.ServerXMLHTTP.6.0")
    WinHttpReq.Open "GET", myURL, False
    WinHttpReq.Send

    myURL = WinHttpReq.ResponseBody
    If WinHttpReq.Status = 200 Then
        Set oStream = CreateObject("ADODB.Stream")
        oStream.Open
        oStream.Type = 2
        oStream.Write WinHttpReq.ResponseBody
        oStream.SaveToFile ("C:\logs.xls")
        oStream.Close
    End If

2 个答案:

答案 0 :(得分:1)

  • 使用二进制流
  • 现代版本的Windows禁止写入C:的根目录,使用不同的路径。

    oStream.Type = 1
    oStream.Write WinHttpReq.ResponseBody
    oStream.SaveToFile Environ$("TEMP") & "\logs.xls" '// users temp dir
    

答案 1 :(得分:0)

我使用Excel 2010和Windows 7。

这种代码有时对我有用。但不是每次都这样。我懂了 HttpReq.Status = 404 经常比 HttpReq.Status = 200

Dim HttpReq As Object

Set HttpReq = CreateObject("Microsoft.XMLHTTP")

HttpReq.Open "GET", myURL, False

Application.Wait Now + TimeValue("0:00:10")

**HttpReq.send**

Application.Wait Now + TimeValue("0:00:05")

myURL = HttpReq.responseBody

**If HttpReq.Status = 200 Then**
    Set oStrm = CreateObject("ADODB.Stream")
    oStrm.Open
    oStrm.Type = 1
    oStrm.Write HttpReq.responseBody
    oStrm.SaveToFile "C:\Users\MiLarsso\Downloads" & "\" & "Narvarotid1.xls", 2 ' 1 = no overwrite, 2 = overwrite
    oStrm.Close
End If

我实际上相信文件在那里,因为它显示在网络浏览器中。如果没有在100毫秒之内找到它,它可能会很快超时。我可以想象连接可能会有点慢。