VBA - 如何从刚刚下载到当前excel文件的excel文件中获取数据

时间:2017-01-26 18:43:59

标签: excel vba excel-vba

我有这个代码可以下载excel文件,但是如何将数据从这个文件传输到我正在运行宏的excel文件中。您会注意到这个站点提供了一个直接下载文件的URL,但我试图弄清楚如何在不通过该路由的情况下执行此操作,因为另一个项目需要它。

非常感谢任何帮助。

Sub GetData()
Dim IE As InternetExplorer
Dim HTMLDoc As HTMLDocument
Dim objElement As HTMLObjectElement

Set IE = New InternetExplorer
With IE
    .Visible = True
    .Navigate "http://www.housepriceindex.ca/default.aspx"
    While .Busy Or .ReadyState <> READYSTATE_COMPLETE: Wend
    .Document.getElementById("lnkTelecharger2").Click
    While .Busy Or .ReadyState <> READYSTATE_COMPLETE: Wend
    Set HTMLDoc = .Document
    Set objElement = HTMLDoc.getElementById("txtEmailDisclaimerEN")
    objElement.Value = "Email Address"
    Set objElement = HTMLDoc.getElementById("lnkAcceptDisclaimerEN")        
    objElement.Click

    ' ... Get CSV somehow ...

    .Quit
End With

Set IE = Nothing
End Sub

1 个答案:

答案 0 :(得分:0)

我在该网站上没有看到任何类型的CSV,但我想你知道它在哪里。只需资助它并将实际的URL映射到下面的示例网址。

Sub DownloadFileWithVBA()

Dim myURL As String
'Right-click on the link named 'Sample Address File'
'Click 'Copy Link Location'
'Paste the link below
myURL = "http://databases.about.com/library/samples/address.xls"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False
WinHttpReq.Send

myURL = WinHttpReq.ResponseBody
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.ResponseBody
    oStream.SaveToFile ("C:\your_path\address.xls")
    oStream.Close

End Sub