VBA-获取网上的资源

用代码实现下载文件,如图片等小文件,如果是大文件的话,速度太慢,不建议用此类方法

具体的实现代码如下

Option Explicit
Public Function getimage()
    Dim strurl As String
    strurl = "http://p5.so.qhimgs1.com/t0161ac92c369a8cefb.jpg" '下载网址
    Dim xmlhttp As Object
    Set xmlhttp = CreateObject("MSXML2.XMLHTTP")
    xmlhttp.Open "GET", strurl, False
    xmlhttp.send
    Do While xmlhttp.readystate <> 4
        DoEvents
    Loop
    Dim b() As Byte '用字节数组来接收,防止出错
    b = xmlhttp.responsebody
    Open ThisWorkbook.Path & "\1.jpg" For Binary As #1 '保存为1.jpg
        Put #1, , b()
    Close
End Function

表格数据的获取,可以直接用“数据”-“获取外部数据”-“自网站”,也可用代码实现,其代码如下

Sub test()
Cells.Delete
 Dim qt As QueryTable
 Set qt = ActiveSheet.QueryTables.Add(Connection:= _
        "URL;http://money.hexun.com/toolcase_stock/index.html#Menu=3_1", Destination _
        :=Range("$A$1"))
    With qt
        .Name = "index.html#Menu=3_1"
        .WebSelectionType = xlSpecifiedTables '选择类型
        .WebFormatting = xlWebFormattingNone '格式,此处为选择格式
        .WebTables = "13" '选择的表格
        .Refresh BackgroundQuery:=False
    End With
End Sub

猜你喜欢

转载自blog.csdn.net/qq_41777527/article/details/81148318
今日推荐