Export Excel To HTML - Convert Tables To HTML - The Analyst Cave - Excel, VBA, Programming and More
Export Excel To HTML - Convert Tables To HTML - The Analyst Cave - Excel, VBA, Programming and More
Me gusta 0
The concept itself is very simple as HTML files are text files and therefore the problem
is only to structure the data correctly in VBA before saving it to a HTML file.
https://analystcave.com/excel-export-excel-to-html-convert-tables-html/ 1/5
10/5/2018 Export Excel to HTML - convert tables to HTML - The Analyst Cave | Excel, VBA, programming and more
Both options are fairly useful ones – with the first one offering more flexibility and the
second one being much easier to use.
Excel table
The Code
1 Sub Test()
2 RangeToHtml Range("A1:C3"), "test.html"
3 End Sub
4
5 Sub RangeToHtml(rng As Range, fileName As String)
6 Dim resBeg As String
7 resBeg = "<html><head></head><body><table>"
8 resEnd = "</table></body></html>"
9 For i = 1 To rng.Rows.Count
10 '---Rows---
11 resBeg = resBeg & "<tr>"
12 For j = 1 To rng.Columns.Count
13 '---Columns---
14 resBeg = resBeg & "<td>"
15 resBeg = resBeg & rng.Cells(i, j).Value
16 resBeg = resBeg & "</td>"
17 Next j
18 resBeg = resBeg & "</tr>"
19 Next i
20 Call SaveStringToFile(resBeg & resEnd, fileName)
21 End Sub
22
23 Sub SaveStringToFile(str As String, fileName As String)
24 Open fileName For Output As #1
25 Print #1, str
https://analystcave.com/excel-export-excel-to-html-convert-tables-html/ 2/5
10/5/2018 Export Excel to HTML - convert tables to HTML - The Analyst Cave | Excel, VBA, programming and more
26 Close #1
27 End Sub
1 2 3
4 5 6
To publish the Excel file go to Save As and select Publish to configure the publish
options:
https://analystcave.com/excel-export-excel-to-html-convert-tables-html/ 3/5
10/5/2018 Export Excel to HTML - convert tables to HTML - The Analyst Cave | Excel, VBA, programming and more
Alternatively you can use the VBA code below to achieve the same:
1 With ActiveWorkbook.PublishObjects.Add(xlSourceRange, _
2 "PublishToHtml.htm", ";Sheet1", "$A$1:$C$4", _
3 xlHtmlStatic, "PublishToHtml", "")
4 .Publish (True)
5 End With
Easy as that! The additional advantage is that the Publish to Excel feature will keep
some of your formatting settings e.g. bold, italic fonts etc. Some, however, usually
will be omitted e.g. borders.
Conclusions
Without resorting to external solutions there are least 2 easy options of generating
html files from Excel. Personally I would prefer to have control over my HTML file and
use VBA possibly adding my own css styles and formatting.
https://analystcave.com/excel-export-excel-to-html-convert-tables-html/ 4/5
10/5/2018 Export Excel to HTML - convert tables to HTML - The Analyst Cave | Excel, VBA, programming and more
Related Posts
https://analystcave.com/excel-export-excel-to-html-convert-tables-html/ 5/5