文章背景:测试仪器的数据有些会以Excel文件的形式保存,有时需要将测试数据转化为pdf格式。通过虚拟打印机(Adobe PDF)可以将excel文件输出为pdf文件。然而,当文件比较多时,这种操作比较费时。现在以批量转化Excel文件(.xlsx格式)为例,采用VBA编程,进行任务的实现。
在批量转化文件
的按钮中指定的宏命令为ConvertFiles。
在模块中添加的代码如下:
代码语言:javascript复制Option Explicit
Sub ConvertFiles()
'批量转化Excel文件为pdf
Dim filefolder As String
Dim fd As FileDialog, t As String, str As String, name As String
Application.ScreenUpdating = False
'获取默认路径
ChDrive ThisWorkbook.Worksheets("Sheet1").Range("B2").Value
ChDir ThisWorkbook.Worksheets("Sheet1").Range("B3").Value
'1 创建储存pdf文件的空文件夹
filefolder = ThisWorkbook.Worksheets("Sheet1").Range("B3").Value & "pdf文件"
If Not isDirectory(filefolder) Then
VBA.MkDir (filefolder)
Else
MsgBox "默认路径的pdf文件夹已存在,请确认!"
Exit Sub
End If
'2 选择需要转化的文件夹路径
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
If .Show = -1 Then
t = .SelectedItems(1)
Else
MsgBox "未选取文件夹!"
Exit Sub
End If
End With
str = Dir(t & "*.xlsx") ' 开始查找文件,格式为xlsx文件
Do While Len(str) > 0
Workbooks.Open (t & "" & str)
name = CreateObject("Scripting.FileSystemobject").getextensionname(str) '获取文件的扩展名
ActiveWorkbook.Worksheets(1).ExportAsFixedFormat Type:=xlTypePDF, _
Filename:=filefolder & "" & Replace(str, name, "pdf"), Quality:=xlQualityStandard, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Workbooks(str).Close False
str = Dir()
Loop
MsgBox "Done!"
Application.ScreenUpdating = False
Exit Sub
End Sub
Function isDirectory(pathName As String) As Boolean
'用于判断文件夹是否存在
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
isDirectory = fso.FolderExists(pathName)
End Function
运行效果展示
运行前:
运行后:
参考资料:
[1] VBA批量转化Excel文件为PDF(http://www.360doc.com/content/17/0909/07/30583536_685669139.shtml)
[2] 批量将Excel转化为PDF(https://blog.csdn.net/sinat_39901027/article/details/109412016)
[3] Workbook.ExportAsFixedFormat method (Excel)(https://docs.microsoft.com/en-us/office/vba/api/excel.workbook.exportasfixedformat)