how to Convert Text file intp pdf file in a folder using VBA code RRS feed

  • Question

  • Sub convertToWord()
       Dim MyObj As Object, MySource As Object, file As Variant
       file = Dir("C:\Text" & "*.txt") 'txt path
       Do While (file <> "")
       ChangeFileOpenDirectory = "C:\Text2"
              Documents.Open Filename:=file, ConfirmConversions:=False, ReadOnly:= _
            False, AddToRecentFiles:=False, PasswordDocument:="", PasswordTemplate:= _
            "", Revert:=False, WritePasswordDocument:="", WritePasswordTemplate:="", _
            Format:=wdOpenFormatAuto, XMLTransform:=""
        ChangeFileOpenDirectory = "C:\Text2" 'path for saving pdf
        ActiveDocument.SaveAs2 Filename:=Replace(file, ".txt", ".pdf"), FileFormat:=wdFormatXMLDocument _
            , LockComments:=False, Password:="", AddToRecentFiles:=True, _
            WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
             SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
            False, CompatibilityMode:=15
         file = Dir
    End Sub
    Wednesday, April 11, 2018 9:54 AM

All replies

  • If you want to save a PDF, then you need to use the appropriate save format - which isn't wdFormatXMLDocument! Try:

    Sub ConvertToPDF()
    Dim file As Variant, wdDoc As Document
    file = Dir("C:\Text" & "*.txt") 'txt path
    Do While (file <> "")
      Set wdDoc = Documents.Open(FileName:="C:\Text" & file, ReadOnly:=True, _
        AddToRecentFiles:=False, Format:=wdOpenFormatAuto, Visible:=False)
      wdDoc.SaveAs2 FileName:="C:\Text2" & Replace(file, ".txt", ".pdf"), _
        FileFormat:=wdFormatPDF, AddToRecentFiles:=False
      wdDoc.Close False
      file = Dir
    End Sub

    Paul Edstein
    [MS MVP - Word]

    Thursday, April 12, 2018 12:47 AM