4
votes

The problem I'm having is when I run my macro to save the current Word Document as a HTML type, the document still remains open but not in the original .docx format, it's in the .htm format.

If I were to edit the document after the macro is ran, it wouldn't remain on the original .docx format later.

I would appreciate feedback on how to remain in the original format when also saving a copy with a different format. Thanks.

Here is my docx to html code in VBA

Sub DocToHTML()

    Dim slice As String
    Dim strDocName As String
    Dim PathOrg As String

    On Error Resume Next

    strDocName = ActiveDocument.Name
    slice = Left(strDocName, InStrRev(strDocName, ".") - 1)
    strDocName = ActiveDocument.Path + "\" + slice
    ActiveDocument.SaveAs2 FileName:=strDocName, FileFormat:=wdFormatHTML

End Sub
1

1 Answers

1
votes

Before you write code to do things like this stop and think how you would do it in the UI without code. Any code that you write will simply automate that process.

So what would you do in the UI?

  1. Save the original document to preserve any changes that you have made.
  2. Save a copy as html.
  3. Reopen the original document.
  4. Possibly close the html version.

So your code can be rewritten as follows:

Sub DocToHTML()

    Dim origName As String
    Dim saveName As String
    Dim docHTML As Document

    If Not ActiveDocument.Saved Then ActiveDocument.Save
    origName = ActiveDocument.FullName
    saveName = Left(origName, InStrRev(origName, ".") - 1)
    ActiveDocument.SaveAs2 FileName:=saveName, FileFormat:=wdFormatHTML

    Set docHTML = ActiveDocument
    Documents.Open origName
    docHTML.Close wdDoNotSaveChanges

End Sub