Wednesday, June 24, 2026

VBA Word - Convert HTML content into a Markdown (MD) file

Run the following VBA Excel program. The program opens chat.html file from source folder in your default browser (e.g. Chrome). Then it selects all its content and paste into a text file. The text file is named the source folder name with file extension .md  and saved into the parent folder.

Sub ConvertChatHtmlToMarkdown()
    Dim fso As Object
    Dim sourceFolder As String
    Dim chatFilePath As String
    Dim parentFolder As String
    Dim folderName As String
    Dim markdownFilePath As String
    Dim htmlContent As String
    Dim ts As Object
    Dim fileContent As String

    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        .Show
        If .SelectedItems.Count <> 1 Then Exit Sub
        sourceFolder = .SelectedItems.Item(1)
    End With


    ' Build full path to chat.html
    chatFilePath = sourceFolder & "\chat.html"

    ' Check if chat.html exists
    If Dir(chatFilePath) = "" Then
        MsgBox "chat.html not found in " & sourceFolder, vbExclamation
        Exit Sub
    End If

    ' Open chat.html in default browser
    ThisWorkbook.FollowHyperlink chatFilePath

    ' Read the HTML file content
    Set ts = fso.OpenTextFile(chatFilePath, 1, False, -2) ' -2 means Unicode/AutoDetect
    htmlContent = ts.ReadAll
    ts.Close

    ' Get folder name and parent folder path
    folderName = fso.GetFolder(sourceFolder).Name
    parentFolder = fso.GetFolder(sourceFolder).parentFolder.Path

    ' Build output .md file path
    markdownFilePath = parentFolder & "\" & folderName & ".md"

    ' Write HTML content to .md file
    Set ts = fso.CreateTextFile(markdownFilePath, True, True) ' Overwrite, Unicode
    ts.Write htmlContent
    ts.Close

    MsgBox "Markdown file created at:" & vbCrLf & markdownFilePath, vbInformation
End Sub

No comments:

Post a Comment

Hot Topics