excelvbams-word

How to convert a text file to PDF using VBA?


I want to convert a list of text files in a particular folder into PDF.

I have written logic to open a single text file from Word document to be saved in a PDF format but it is not saved as a PDF file.

This is Excel VBA.

Dim file As Variant
inp_dir = "C:\Users\HP\OneDrive\Desktop\vbatest\pdfconv\"
inp_file_name = Dir(inp_dir & "*.txt") 'txt path
inp_file = inp_dir & inp_file_name

Dim wdApp As New Word.Application, wdDoc As Word.Document

MsgBox (inp_file)

' Set wdDoc = Documents.Open(inp_file)
Set wdDoc = Documents.Open(Filename:=inp_file, ReadOnly:=True, _
  AddToRecentFiles:=False, Format:=wdOpenFormatAuto, Visible:=False)
  
wdDoc.SaveAs2 Filename:="inp_file" & Replace(inp_file, ".txt", ".pdf"), _
  FileFormat:=wdFormatPDF, AddToRecentFiles:=False
wdDoc.Close False

Solution

  • I guess you are close - you just have a small mistake in your destination file name: You write Filename:="inp_file" & Replace(inp_file, ".txt", ".pdf"), but the fixed string "inp_file" makes no sense and invalidates the filename.

    I always advice to use intermediate variables, with that it gets much easier to debug and to find errors.

    Some more small things:

    Your code could look like:

    Const inp_dir = "C:\Users\HP\OneDrive\Desktop\vbatest\pdfconv\"
    
    Dim inp_file_name As String, inp_full_name As String
    
    inp_file_name = Dir(inp_dir & "*.txt") 'txt path
    inp_full_name = inp_dir & inp_file_name
    
    Dim wdApp As New Word.Application, wdDoc As Word.Document
    Set wdDoc = wdApp.Documents.Open(Filename:=inp_full_name, ReadOnly:=True, _
        AddToRecentFiles:=False, Format:=wdOpenFormatAuto, Visible:=False)
      
    Dim pdf_Filename As String
    pdf_Filename = Replace(inp_full_name, ".txt", ".pdf")
    Debug.Print pdf_Filename 
    wdDoc.SaveAs2 Filename:=pdf_Filename, FileFormat:=wdFormatPDF, AddToRecentFiles:=False
    wdDoc.Close False
    
    wdApp.Quit