文章背景:通过Printout
函数,可以将Excel文件转换为pdf文件,但与此同时,该函数可能会通过ActivePrinter
参数将默认打印机修改为Microsoft Print to PDF
。借助Application.ActivePrinter
属性,一方面可以查询当前默认打印机的名称,另一方面,也可以指定默认打印机的名称。
(1) Application.ActivePrinter
Returns or sets the name of the active printer. Read/write String.
(2) 代码示例
Option Explicit
Sub getPrinterName()
Dim Printer_original As String
Dim Path As String, path_saved As String, name_file As String
'1 记录最开始的默认打印机
Printer_original = Application.ActivePrinter
'2 将一份excel文件转化为pdf文件
Path = "E:\工作\报告展示\1.xlsx"
path_saved = "E:\工作\报告展示\1.pdf"
name_file = "1.xlsx"
Workbooks.Open (Path)
ActiveWorkbook.Worksheets(1).PrintOut copies:=1, preview:=False, ActivePrinter:="Microsoft Print to PDF" _
, PrintToFile:=True, PrToFileName:=path_saved, IgnorePrintAreas:=False
Workbooks(name_file).Close False
'3 恢复默认的打印机
Application.ActivePrinter = Printer_original
End Sub
该代码主要分为三步:(1)先记录当前默认打印机的名称,一般电脑默认连接的是实体打印机;(2)借助Printout函数将指定的Excel文件转换为PDF文件,此时默认打印机的名称已经发生变化,转变成了Microsoft Print to PDF
; (3)恢复默认的打印机,也就是第(1)步保存的打印机名称。
参考资料:
[1] Application.ActivePrinter property(https://docs.microsoft.com/en-us/office/vba/api/excel.application.activeprinter)
延伸阅读: