2016-11-18 147 views
0

我是VBA编码的新手,但想知道如何在Excel中创建一个宏,允许我选择一个文件夹中有rtf文件,并将它们全部转换为相同文件夹中的pdf。Excel VBA代码批量转换文件夹中的rtf文件为pdf文件

任何帮助表示赞赏。

亲切的问候

+0

虽然你的问题措辞相当好,但它没有显示任何研究工作。在这种情况下,我已经帮助过你,但堆栈不应该是你的问题的出发点,谷歌应该是。 –

回答

0

要做到这一点,最简单的方法是使用Word打开该.rtf并将其转换为PDF。 Excel旨在显示电子表格而不是文档,但您可以通过引用Word对象库来自动执行此操作。

使用内置的FileDialog提示您选择文件夹,并作为宏的入口点。

'Add a Reference Microsoft Word Object Library 

Sub ConvertRtfToPDF() 

    With Application.FileDialog(msoFileDialogFolderPicker) 
     .AllowMultiSelect = False 
     If .Show() Then 
      ConvertFiles GetFiles(.SelectedItems(1), ".rtf") 
     End If 
    End With 

End Sub 

这是做转换的功能,它需要的文件的阵列,并将它们全部转换为PDF:

Sub ConvertFiles(files() As String) 

    Dim wd As New Word.Application 
    Dim doc As Word.Document 
    Dim file As Variant 

    For Each file In files 
     Set doc = wd.Documents.Open(file, ReadOnly:=True) 
     doc.ExportAsFixedFormat Replace(file, ".rtf", ".pdf"), 17 
     doc.Close 
    Next file 

    wd.Quit 

End Sub 

该函数返回的文件名的数组,给定一个文件夹名称:

Function GetFiles(folder As String, extension As String) As String() 

    Dim files() As String 
    ReDim files(0) 

    file = Dir(folder & "\") 
    While (file <> "") 
     If Right(file, Len(extension)) = extension Then 
      files(UBound(files)) = folder & "\" & file 
      ReDim Preserve files(UBound(files) + 1) 
     End If 
     file = Dir 
    Wend 
    ReDim Preserve files(UBound(files) - 1) 
    GetFiles = files 

End Function 

粘贴所有到模块并运行ConvertRtfToPDF功能,系统会提示您选择一个文件夹,它会在该文件夹中的每个.rtf转换为.pdf