2016-11-18 65 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

相關問題