VBA批量将Excel转换为PDF

Excel 2010和Excel 2007可以将Excel工作簿另存为PDF格式文件,但手工的方法每次只能转换一个工作簿,要转换多个工作簿就显得有些繁琐。如果没有批量转换软件,在Excel 2010和Excel 2007中,利用VBA代码也可以轻松实现将Excel工作簿批量转换为PDF,方法如下:
1.按Alt+F11,打开VBA编辑器。
2.在右侧代码窗口中输入下列代码:

Sub BatchConvertWorkBookToPDF()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
    Dim fDialog As FileDialog
    Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
    Dim vrtSelectedItem As Variant
    Dim wkBook As Workbook
    Dim showFolder  As Boolean
    showFolder = False
    With fDialog
        .Filters.Add "Excel文件", "*.xls; *.xlsx; *.xlsm", 1
        If .Show = -1 Then
            For Each vrtSelectedItem In .SelectedItems
                '如果选择了本工作簿则跳过
                If InStrRev(vrtSelectedItem, ThisWorkbook.Name) = 0 Then
                    On Error Resume Next
                    Set wkBook = Application.Workbooks.Open(vrtSelectedItem, ReadOnly:=True, Password:="")
                    '跳过设置打开密码的工作簿
                    If Not wkBook Is Nothing Then
                       '跳过隐藏的工作簿
                       If Windows(wkBook.Name).Visible = True Then
                       showFolder = True
                       '转换开始
                       wkBook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
                          Left(vrtSelectedItem, InStrRev(vrtSelectedItem, ".") - 1) & ".pdf" _
                          , Quality:=xlQualityMinimum, IncludeDocProperties:=False, IgnorePrintAreas _
                          :=True, OpenAfterPublish:=False
                       wkBook.Close , savechanges = False
                       wkBook.Close , savechanges = False
                       End If
                    End If
               End If
            Next vrtSelectedItem
            If showFolder Then Call Shell("explorer.exe " & Left(fDialog.SelectedItems(1), _
                InStrRev(fDialog.SelectedItems(1), "")), vbMaximizedFocus)
        End If
    End With
    Set fDialog = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

3.将需要转换的Excel工作簿复制到某个文件夹中。
4.关闭VBA编辑器返回Excel界面。按Alt+F8打开“宏”对话框,执行“BatchConvertWorkBookToPDF”宏。
5.在弹出的“浏览”对话框中选择包含要转换工作簿的文件夹,选择所有要转换的工作簿,单击“打开”按钮即可开始转换。