应用场景
批量将excel文件转换为PDF格式文件
知识要点
1:Workbooks.Open 文件路径,打开文件路径的文件
2:GetExtensionName 方法 返回一个包含路径中最后部件扩展名的字符串。
3:Workbook.ExportAsFixedFormat 方法 用于将工作簿发布为 PDF 或 XPS 格式。
4:Kill 语句 从磁盘中删除文件。
Sub 批量将Excel文件转成PDF()
Dim str As String, n As Long, fd, nam As String, t
On Error GoTo err '程序出错时退出
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd '显示一个文件夹的对话框,如果选择了文件夹则取其名称,否则退出
If .Show = -1 Then t = .SelectedItems(1) Else Exit Sub
End With
Application.ScreenUpdating = False '关闭屏幕刷新,提示速度
str = Dir(t & '\*.xl*') '开始查找文件,格式为所有excel文件
While Len(str) > 0
n = n 1
Workbooks.Open (t & IIf(Right(t, 1) = '\', '', '\') & str) '打开工作薄
'filesystemobject 提供对计算机文件系统的访问,getextensionname方法,返回一个包含路径中最后部件扩展名的字符串。
nam = CreateObject('Scripting.FileSystemobject').getextensionname(str) '获取文件的扩展名
'开始进行格式转换,两个参数分别表示文件名,转换质量
'workbook.exportasfixedformat方法,用于将工作薄发布为PDF或XPS格式
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, filename:=(t & IIf(Right(t, 1) = '\', '', '\') & Replace(str, nam, 'pdf')), Quality:=xlQualityStandard
Workbooks(str).Close False '关闭工作薄
Kill (IIf(Right(t, 1) = '\', '', '\') & str) '删除工作薄
str = Dir() '查找下一个
Wend
Application.ScreenUpdating = True
err:
End Sub
'exportasfixedformat方法包括工作薄级和工作表级,工作薄级的exprotasfixedformat可以将整个工作薄中所有工作表转换成PDF,而工作表级的exprotasfixedformat仅仅对
'当前表生效,workbook.exportfixedformat方法用于将工作薄发布为PDF或xps格式,语法如下
'表达式.exportasfixedformat(type,filename,quality,includedocproperties,ignoreprintareas,form,to,openafterpublish,fixedformatextclassptr)
'type 必选,可以是xltypePDF,也可以是xltypexps
'filename 可选,一个字符串,指示要保存的文件的名称,也可以包括完整路径,否则excel会将文件保存在当前文件夹中
联系客服