Excel VBA工作簿打印输出方法

fivyi3re  于 2023-02-20  发布在  其他
关注(0)|答案(2)|浏览(211)

我正在编写一个VBA宏,用于将excel工作簿转换为PDF。wkb.PrintOut方法适用于某些excel文件。但对于其他excel文件,它会将第一个工作表打印到我提供的文件名,并提示我输入要保存其余工作表的文件名。
为什么PrintOut函数会有这样的行为?如何让它将整个工作簿打印到我设置的单个文件名中?

Public Sub ConvertToPDF()
Dim ws As Worksheet
Dim inputQueue As Collection
Dim outputQueue As Collection
Dim r As Integer, c As Integer
Dim objFSO As FileSystemObject
Dim objInputFolder As Folder
Dim objOutputFolder As Folder
Dim objInputFile As File
Dim fileExt As String

Set ws = Worksheets("XLPrint")
Set objFSO = New FileSystemObject
Set inputQueue = New Collection
Set outputQueue = New Collection
Application.ActivePrinter = "Microsoft Print to PDF on Ne02:"

Application.DisplayAlerts = False
r = ws.Range("folder_name").Row + 1
c = ws.Range("folder_name").Column

ClearCollection inputQueue
ClearCollection outputQueue

While (ws.Cells(r, c).Value <> "")
    inputQueue.Add objFSO.GetFolder(ws.Cells(r, c).Value)
    outputQueue.Add objFSO.GetFolder(ws.Cells(r, c + 1).Value)
    r = r + 1
Wend

Application.ScreenUpdating = False

Do While inputQueue.Count > 0
    Set objInputFolder = inputQueue(1)
    inputQueue.Remove 1
    Set objOutputFolder = outputQueue(1)
    outputQueue.Remove 1

    For Each objInputFile In objInputFolder.Files
        fileExt = Mid(objInputFile.ShortName, InStr(objInputFile.ShortName, ".") + 1)
        Select Case UCase(fileExt)
            Case "XLSX", "XLSM", "XLS"
                Call PrintXLToPDF(objInputFile, objOutputFolder)
            Case "DOCX", "DOC"
                Call PrintWordToPDF(objInputFile, objOutputFolder)
        End Select
    Next objInputFile
Loop
Application.ScreenUpdating = True

Application.DisplayAlerts = True
Set objFSO = Nothing
Set ws = Nothing
Set inputQueue = Nothing
Set outputQueue = Nothing
MsgBox "Done"

End Sub

Public Sub PrintXLToPDF(ByVal objInputXL As File, ByVal objOutputFolder As Folder)

Dim wkb As Workbook
Dim outputFileName As String

Set wkb = Workbooks.Open(objInputXL.Path)
outputFileName = objOutputFolder.ShortPath & "\" & Mid(objInputXL.Name, 1, InStr(objInputXL.Name, ".") - 1) & ".pdf"
wkb.PrintOut Copies:=1, Collate:=True, IgnorePrintAreas:=False, PrToFileName:=outputFileName, ActivePrinter:="Microsoft Print to PDF on Ne02:"
wkb.Close SaveChanges:=False

Set wkb = Nothing
End Sub
aydmsdu9

aydmsdu91#

尝试直接将其保存为PDF,而不是打印:

wkb.ExportAsFixedFormat Type:=xlTypePDF, Filename:=outputFileName, Quality:=xlQualityStandard
pkwftd7m

pkwftd7m2#

多谢
我把Plagon的答案和HackSlash的答案结合起来,问题就解决了
当您保存工作簿(ActiveWorkbook.Save),然后使用HackSlash建议的行(wkb.ExportAsFixedFormat类型:=xlTypePDF,文件名:=outputFileName,质量:=xlQualityStandard)时,问题就解决了

相关问题