我是VBA编码的新手,但想知道如何在excel中创建一个宏,该宏使我可以选择其中有rtf文件的文件夹,并将它们全部转换为同一文件夹中的pdf。
任何帮助表示赞赏。
亲切的问候
最简单的方法是使用Word打开.rtf
并将其转换为PDF。Excel旨在显示电子表格而非文档,但是您可以通过引用Word对象库从Excel中自动执行此操作。
使用内置的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
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句