Copying a web page with an Excel 365 macro

Solved
mikel831 Posted messages 237 Registration date   Status Member Last intervention   -  
mikel831 Posted messages 237 Registration date   Status Member Last intervention   -

Hello!
I have a macro that opens a webpage.
How, in VBA code, can I completely copy this page and then paste it into an Excel sheet starting from cell A1 (for example)?

1 answer

  1. CCMBot
     
    Hello!
    The AI that loves challenges is here!
    To copy a web page using VBA in Excel 365, you can use the QueryTables or InternetExplorer objects. However, Excel may not format the HTML correctly depending on the website. Here’s how to do it with QueryTables:

    ```
    Sub CopyWebPage()
    Dim qt As QueryTable
    Dim url As String

    ' define the URL of the website to copy
    url = "http://www.example.com"

    ' add a QueryTable...
    Set qt = ActiveSheet.QueryTables.Add(Connection:="URL;" & url, Destination:=Range("A1"))

    ' configure the QueryTable...
    With qt
    .WebSelectionType = xlEntirePage '... to select the entire page
    .Refresh BackgroundQuery:=False '... to refresh the data and paste it into the sheet
    End With

    ' release the QueryTable object
    Set qt = Nothing
    End Sub
    ```

    This should automatically paste the entire web page at the specified URL into cell A1 of the active sheet.

    Note: Ensure you have an active internet connection and that the URL you specify is valid and accessible.

    If you want to avoid using QueryTables, you can use InternetExplorer.Application with HTMLDocument and HTMLBody. Here’s how you can accomplish this:

    ```
    Sub CopyWebPage()
    Dim IE As Object, html As Object

    ' Create a new Internet Explorer
    Set IE = CreateObject("InternetExplorer.Application")

    ' URL of the page to copy
    IE.Navigate "http://www.example.com"

    ' Wait for IE to finish loading the page
    Do While IE.Busy Or IE.readyState 4
    Application.Wait DateAdd("s", 1, Now)
    Loop

    ' Copy the text from the page
    Set html = IE.document.all
    html.Select
    html.CopyToClipboard

    ' Paste the information into Excel
    Range("A1").PasteSpecial

    ' Quit IE
    IE.Quit
    Set IE = Nothing
    Set html = Nothing
    End Sub
    ```
    For this code, it is recommended to add a reference to "Microsoft HTML Object Library" by using "Tools -> References" in the VBA editor.
    Also, make sure not to navigate to other pages with Internet Explorer while the macro is running.

    0
    1. mikel831 Posted messages 237 Registration date   Status Member Last intervention   19
       

      Hello!
      I opted for the QueryTable, and it works well.
      However, in some cases, the images and icons on the web page interfere with the copy. Is it possible to remove them when copying the QT?

      0