Option Explicit On Option Strict Off ' Using late binding. Imports System Imports EnvDTE Imports System.Diagnostics Public Module Module1 Private Const WdPasteDefault As Integer = 0 Private Const WdFormatFilteredHTML As Integer = 10 Private Const WdWebView As Integer = 6 Sub FormatSourceCode() ' Get the currently selected code snippet. Dim selection As TextSelection = CType(DTE.ActiveDocument.Selection(), TextSelection) ' Check that something is selected. If selection.Text = "" Then MsgBox("No code selected!", MsgBoxStyle.Critical Or MsgBoxStyle.OKOnly, "Format Code") Return End If ' Create a temporary file. Dim path As String = System.IO.Path.GetTempFileName() ' Copy the selected code to clipboard (using VS.NET). selection.Copy() ' Instantiate a new Word document to achieve HTML code formatting. Dim oleDocument As Type = Type.GetTypeFromProgID("Word.Document") Dim document As Object = Activator.CreateInstance(oleDocument) document.ActiveWindow.Selection.PasteAndFormat(WdPasteDefault) document.SaveAs(path, WdFormatFilteredHTML, False, "", True, "", False, False, False, False, False) document.Close() document = Nothing oleDocument = Nothing ' Open a new instance of Word. Dim oleApplication As Type = Type.GetTypeFromProgID("Word.Application") Dim application As Object = Activator.CreateInstance(oleApplication) ' Open the temporary document. document = application.Documents.Open(path) ' Switch to the WebView mode within Word. document.ActiveWindow.View.Type = WdWebView ' Select the whole document. document.ActiveWindow.Selection.WholeStory() ' Copy it to the clipboard. document.ActiveWindow.Selection.Copy() ' Close the document. document.Close() document = Nothing application.Quit() application = Nothing oleApplication = Nothing ' Cleanup after ourselves. IO.File.Delete(path) End Sub End Module