Tuesday, December 24, 2024

VBA Word - how to generate HTML file

The following VBA code explains how to generate HTML file:
Option Explicit
 
'declare all variables
Dim objWord
Dim oDoc
Dim objFso
Dim colFiles
Dim curFile
Dim curFileName
Dim folderToScanExists
Dim folderToSaveExists
Dim objFolderToScan
 
'set some of the variables
folderToScanExists = False
folderToSaveExists = False
Const wdSaveFormat = 10 'for Filtered HTML output
 
'**********************************
'change the following to fit your system
Const folderToScan = "C:\Word\documentation\"
Const folderToSave = "C:\Inetpub\wwwroot\word\"
'**********************************
 
'Use FSO to see if the folders to read from
'and write to both exist.
'If they do, then set both flags to TRUE,
'and proceed with the function
Set objFso = CreateObject("Scripting.FileSystemObject")
If objFso.FolderExists(folderToScan) Then
  folderToScanExists = True
Else
  MsgBox "Folder to scan from does not exist!", 48, "File System Error"
End If
If objFso.FolderExists(folderToSave) Then
  folderToSaveExists = True
Else
  MsgBox "Folder to copy to does not exist!", 48, "File System Error"
End If
 
If (folderToScanExists And folderToSaveExists) Then
  'get your folder to scan
  Set objFolderToScan = objFso.GetFolder(folderToScan)
  'put al the files under it in a collection
  Set colFiles = objFolderToScan.Files
  'create an instance of Word
  Set objWord = CreateObject("Word.Application")
  If objWord Is Nothing Then
    MsgBox "Couldn't start Word.", 48, "Application Start Error"
  Else
    'for each file
    For Each curFile in colFiles
      'only if the file is of type DOC
      If (objFso.GetExtensionName(curFile) = "doc") Then
        'get the filename without extension
        curFileName = curFile.Name
        curFileName = Mid(curFileName, 1, InStrRev(curFileName, ".") - 1)
        'open the file inside Word
        objWord.Documents.Open objFso.GetAbsolutePathName(curFile)
        'do all this in the background
        objWord.Visible = False
        'create a new document and save it as Filtered HTML
        Set oDoc = objWord.ActiveDocument
        oDoc.SaveAs folderToSave & curFileName & ".htm", wdSaveFormat
        oDoc.Close
        Set oDoc = Nothing
      End If
    Next
  End If
  'close Word
  objWord.Quit
  'set all objects and collections to nothing
  Set objWord = Nothing
  Set colFiles = Nothing
  Set objFolderToScan = Nothing
End If
 
Set objFso = Nothing

No comments:

Post a Comment

Hot Topics