0

I am very new too VBA and I am trying to automate converting word documents to pdf files. I have figured out how to convert all word documents within a single folder to pdf. Now I am struggling to apply that methodology to word documents across all subfolders in a directory. Is there a way to incorporate that in the code below? To add to it, can we pick specific word documents in these folders and convert them to pdf?

Sub BatchConvertDocxToPDF()
  Dim objDoc As Document
  Dim strFile As String, strFolder As String
 
  'Initialization
  strFolder = "C:\Users\Test\Desktop\Test Files\"
  strFile = Dir(strFolder & "*.docx", vbNormal)
 
  'Precess each file in the file folder and convert them to pdf.
  While strFile <> ""
    Set objDoc = Documents.Open(FileName:=strFolder & strFile)
 
    objDoc.ExportAsFixedFormat _
      OutputFileName:=Replace(objDoc.FullName, ".docx", ".pdf"), _
      ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, _
      Range:=wdExportAllDocument, Item:=wdExportDocumentContent
 
    objDoc.Close
    strFile = Dir()
  Wend
End Sub
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45
user13350731
  • 37
  • 1
  • 2
  • There are several questions on here on how to "Loop Through All Subfolders", so just search for that and you should get a couple of ways to do it. [this](https://stackoverflow.com/questions/9827715/get-list-of-sub-directories-in-vba) and [this](https://stackoverflow.com/questions/14245712/cycle-through-sub-folders-and-files-in-a-user-specified-root-directory) and [this](https://stackoverflow.com/questions/22645347/loop-through-all-subfolders-using-vba). And if you want to pick something specific, then just speciy that instead of the current "all" `While strFile <> ""` – Christofer Weber Oct 13 '21 at 09:38
  • Does this answer your question? [Cycle through sub-folders and files in a user-specified root directory](https://stackoverflow.com/questions/14245712/cycle-through-sub-folders-and-files-in-a-user-specified-root-directory) – Eugene Astafiev Oct 13 '21 at 22:50
  • See the second part of https://wordmvp.com/FAQs/MacrosVBA/BatchFR.htm about using the FileSearch object instead of Dir. That page is about find and replace but the same method could be used for saving as pdf. – Charles Kenyon Oct 14 '21 at 00:31

0 Answers0