Building a Macro to Download Data off a Website into Excel

空扰寡人 提交于 2019-12-05 07:52:44

问题


I would like to build a macro in Excel using VBA to download historical data off the following website:

http://quickstats.nass.usda.gov/results/320F1D82-1064-30F1-809E-F77E509EC508

I first create a command button as usual. I then thought this may be able to be easily solved using a macro recorder. However when I select Data -> Get External Data -> From Web and then type in the above address I am unable to select the table as a whole as the data.

So, I am unsure how to do this task otherwise but I feel there may be some standard code somewhere, which I have been unable to find, in order to complete the task.

I feel that this task is useful to many people, as scripts to download data off websites can be used in a variety of places.


回答1:


There are lots of ways of getting data from a website using VBA. You can navigate to it using an InternetExplorer object and parse the HTML once you're there. You can also craft HTTP requests using MSXML2.XMLHTTP. Excel in particular has a number of data-link options that can do this.

However, here I'd use the tools that the UDSA have ever-so-kindly provided for you, and do it in one line:

Workbooks.Open ("http://quickstats.nass.usda.gov/data/spreadsheet/4C43034A-0EAA-3171-B4FC-84CC95FC6E0C.csv")

EDIT: In response to Sandstone's question below, here's some code to copy data from that workbook into your existing one.

Dim thisWb, downloadWb As Workbook
Set thisWb = ActiveWorkbook

Set downloadWb = Workbooks.Open("http://quickstats.nass.usda.gov/data/spreadsheet/4C43034A-0EAA-3171-B4FC-84CC95FC6E0C.csv")

downloadWb.Worksheets(1).Range("A1:U2613").Copy Destination:=thisWb.Worksheets(1).Range("A2")

downloadWb.Close

Of course, you'll want to change the ranges and so on to match the data you need.




回答2:


Instead of trying to download a dynamic table, you can try downloading the table from the "printable" version of the table instead. The URL for the printable table was;

Blockquote http://quickstats.nass.usda.gov/results/320F1D82-1064-30F1-809E-F77E509EC508

and with VBA;

With ActiveSheet.QueryTables.Add(Connection:= _
    "URL;http://quickstats.nass.usda.gov/data/printable/4C43034A-0EAA-3171-B4FC-84CC95FC6E0C" _
    , Destination:=Range("$F$10"))

I could download the table with a macro.




回答3:


It's because what looks like a table is in fact a stack of lots of single-line tables, generated dynamically (you can see that when you scroll down), buried in >= 8 levels of <div>.

Use e.g. Firefox and "Inspect element" to see the page structure.

So this page is a particularly bad example for the task you want to do.



来源:https://stackoverflow.com/questions/32167545/building-a-macro-to-download-data-off-a-website-into-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!