Skip to content

Instantly share code, notes, and snippets.

@shapiromatron
Last active July 12, 2023 02:43
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save shapiromatron/5024948 to your computer and use it in GitHub Desktop.
Save shapiromatron/5024948 to your computer and use it in GitHub Desktop.
Convert an Excel Range to a Bootstrap HTML table
' Example function call: =BuildHTMLTable(A1:D5)
Public Function BuildHTMLTable(rng As Range) As String
' Given a Range of Cells, build a Bootstrap HTML table, using the formatting
' specified in the Excel cells. If "header" is specified to equal true, assumes
' the first row in the table is a header row.
Dim last_r As Long: last_r = rng.Cells(1, 1).Row
Dim tds As New Collection
Dim txt As String
Dim isFirstRow As Boolean: isFirstRow = True
Dim cell As Range, r As Long
txt = "<table class=" & Chr(34) & _
"table table-compressed table-striped" & Chr(34) & ">" & vbNewLine
For Each cell In rng
r = cell.Row
If (r <> last_r) Then
If isFirstRow Then
txt = txt & vbTab & "<thead>" & vbNewLine & BuildRow(tds, isFirstRow) & vbTab & _
"</thead>" & vbNewLine & vbTab & "<tbody>" & vbNewLine
Else
txt = txt & BuildRow(tds, isFirstRow)
End If
isFirstRow = False
Set tds = New Collection
End If
tds.Add cell.Text
last_r = r
Next
txt = txt & BuildRow(tds, isFirstRow)
txt = txt & vbTab & "</tbody>" & vbNewLine & "</table>" & vbNewLine
BuildHTMLTable = txt
End Function
Private Function BuildRow(tds As Collection, header As Boolean) As String
' Build a single HTML row given a collection of tds
Dim txt As String: txt = vbTab & vbTab & "<tr>"
Dim start_tag As String, end_tag As String, td As Variant
If header Then
start_tag = "<th>"
end_tag = "</th>"
Else
start_tag = "<td>"
end_tag = "</td>"
End If
For Each td In tds
txt = txt & start_tag & td & end_tag
Next
txt = txt & "</tr>" & vbNewLine
BuildRow = txt
End Function
@JMFit
Copy link

JMFit commented Jul 12, 2023

Sorry to revive an old thread - I use this function and love it!

I was wondering if there may be any way to amend the function such that hyperlinks in Excel cells are retained.

So, for a cell containing the text 'Google' with hyperlink to 'www.google.com', instead of outputting:
<td>Google</td>

What I am ideally hoping for instead is this:
<td><a href="www.google.com" target="_blank">Google</a></td>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment