在GetWebTable中使用单元格引用进行连接

时间:2017-10-20 15:11:40

标签: excel-vba web-scraping reference web vba

我试图从WSJ期货中提取表格,但我希望能够更改网址中的日期。我希望使用下面的代码,但使网站成为单元格引用。有关如何使这项工作或不同的代码的任何想法,将得到与网站的单元格引用相同的结果?

Sub GetWebTable()
    With ActiveSheet.QueryTables.Add(Connection:="http://www.wsj.com/mdc/public/page/2_3023-fut_metal-futures-20170901.html?mod=mdc_pastcalendar", Destination:=Range("a1"))
        .Refresh BackgroundQuery:=False
        .SaveData = True
    End With
End Sub

1 个答案:

答案 0 :(得分:0)

试试这个。它会把你带到桌子上。仔细查看脚本中的Connection:="URL;" & URL,部分。你搞砸了。

Sub GetWebTable()
    Dim URL As String
    URL = "http://www.wsj.com/mdc/public/page/2_3023-fut_metal-futures-20170901.html?mod=mdc_pastcalendar"

    With ActiveSheet.QueryTables.Add(Connection:="URL;" & URL, Destination:=Range("A1"))
        .Refresh BackgroundQuery:=False
        .SaveData = True
    End With
End Sub

编辑:

如果你想要解析除了所有特定表之外的任何特定表,你只需要找到它的索引号,就像我在下面所做的那样:

Sub GetWebTable()
    Dim URL As String
    URL = "http://www.wsj.com/mdc/public/page/2_3023-fut_metal-futures-20170901.html?mod=mdc_pastcalendar"

    With ActiveSheet.QueryTables.Add(Connection:="URL;" & URL, Destination:=Range("A1"))
        .WebTables = "3" 'You can parse any specific table as well. For more than one table change the parameter "2,3" like this
        .Refresh
    End With

End Sub