简体   繁体   中英

Excel VBA - Separate data from function to-> cell

I'm just learning VBA . I want to make some tool that scrap from internet to sheet.

I just read few tutorials, and got that function made in Modules:

Sub URL_Static_Query()

    With ActiveSheet.QueryTables.Add(Connection:= _
        "URL;https://randompage.com", _
        Destination:=Range("j20"))

        .BackgroundQuery = True

        .TablesOnlyFromHTML = True

        .Refresh BackgroundQuery:=False

        .SaveData = True
    End With

End Sub

Now all I want is to use extract data before it writes to cell. Any ideas?

Instead of extracting data from a website using a query, you can try scraping a website's HTML as follows:

Sub ImportData()
    'to refer to the running copy of Internet Explorer
    Dim IE As InternetExplorer
    'to refer to the HTML document returned
    Dim html As HTMLDocument
    'open Internet Explorer in memory, and go to website
    Set IE = New InternetExplorer
    IE.Visible = False
    IE.Navigate "https://randompage.com"
    'Wait until IE is done loading page
    Do While IE.ReadyState <> READYSTATE_COMPLETE
        Application.StatusBar = "Trying to go to StackOverflow ..."
    DoEvents
    Loop
    'show text of HTML document returned
    Set html = IE.Document
    MsgBox html.DocumentElement.innerText  '--> do your stuff here

    'close down IE and reset status bar
    Set IE = Nothing
    Application.StatusBar = ""
End Sub

To run the above code you'll have to add reference to following two object libraries:

1. Microsoft Internet Controls
2. Microsoft HTML Object Library

You can add reference in VBE. Click on Tools menu and select References . Then check both the libraries. See the image below:

在此输入图像描述

Got help from here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM