Convert HTML-table to Excel using VBA

后端 未结 9 2089
难免孤独
难免孤独 2021-02-05 02:51

Convert HTML-table to Excel

The code below fetches the HTML-table at https://rasmusrhl.github.io/stuff, and converts it to Excel-format.

The pr

9条回答
  •  抹茶落季
    2021-02-05 03:10

    Processing the HTML and then Copying and Pasting it into Excel will

    Here are the steps I used:

    • CreateObject("MSXML2.XMLHTTP"): get the URL's responseText
    • CreateObject("HTMLFile"): create a HTML Document from responseText
    • Replace grey with black to darken the borders
    • Prefix columns s1 and s2 with @ to preserve formatting
    • Copy the HTML to the Windows Clipboard
      • Note: The HTML need to enclosed in HTML and Body tags to paste properly
    • Setup the destination Worksheet
    • Paste the HTML into the Worksheet
    • Replace the @ sign with '
      • Note: This preserves the formatting by storing the data as text
    • Finish formatting the Worksheet


    Sub LoadTable()
        Const URL = "https://rasmusrhl.github.io/stuff/"
        Dim x As Long
        Dim doc As Object, tbl As Object, rw As Object
        With CreateObject("MSXML2.XMLHTTP")
            .Open "GET", URL, False
            .send
            If .readyState = 4 And .Status = 200 Then
                Set doc = CreateObject("HTMLFile")
                doc.body.innerHTML = .responseText
                doc.body.innerHTML = Replace(doc.body.innerHTML, "grey", "black")
                Set tbl = doc.getElementsByTagName("TABLE")(0)
    
                For x = 0 To tbl.Rows.Length - 1
                    Set rw = tbl.Rows(x)
    
                    If rw.Cells.Length = 14 Then
                        'If InStr(rw.Cells(12).innerText, "-") Or InStr(rw.Cells(12).innerText, "/") Then
                        rw.Cells(12).innerText = "@" & rw.Cells(12).innerText
                        rw.Cells(13).innerText = "@" & rw.Cells(13).innerText
                    End If
                Next
    
                With CreateObject("new:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
                    .SetText "" & doc.body.innerHTML & ""
                    .PutInClipboard
                End With
    
                With Worksheets("Sheet1")
                    .Cells.Clear
                    .Range("A1").PasteSpecial
                    .Cells.Interior.Color = vbWhite
                    .Cells.WrapText = False
                    .Columns.AutoFit
                    .Columns("M:N").Replace What:="@", Replacement:="'"
                End With
    
            Else
                MsgBox "URL:  " & vbCrLf & "Ready state: " & .readyState & vbCrLf & "HTTP request status: " & .Status, vbInformation, "URL Not Responding"
            End If
        End With
    End Sub
    

提交回复
热议问题