VBA从自定义程序打印到PDF

时间:2018-05-24 15:58:40

标签: vba ui-automation

在工作中,我们有一个自定义程序,可以从我们的数据库生成报告。 我们不允许安装新的语言包或引用,但我设法使用excel的基础UIAutomation自动生成报告,但是这个报告需要在目录中保存为pdf,就像他们这样做它们点击CTRL + P并选中打印机名称为“Microsoft Print to PDF”。有没有办法只使用VBA自动执行此步骤?

如果有任何帮助,我的代码如下:

gp + geom_ribbon(data = pdat, aes(ymin = low, ymax = up, group = cyl, fill = 'mod'), alpha = 0.3) + 
scale_fill_manual(values=c("orange"), name="model")

1 个答案:

答案 0 :(得分:0)

假设 CTRL + p 是自定义应用程序中用于打开打印对话框的相应热键,您可以使用SendKeys来破解它

Dim filename as String
filename = "c:/path/to/my filename" ' do not need to include the .PDF extension

' Open the print dialog
SendKeys "^p", True
' Select your printer (this may not be necessary, but since we don't know
' anything about your application or what it's print dialog looks like, 
' you'll have to probably make some changes 
SendKeys "{ENTER}", True
' Once the printer has been selected, send the filename to the dialog
SendKeys filename, True
' Sending ENTER again should execute the Print to PDF
SendKeys "{ENTER}"

注意这假定“Microsoft Print to PDF”是默认打印机。如果情况并非如此,并且您的应用程序未提供API,则可能仍有一种方法可以使用FindWindow / etc和其他更复杂的WinAPI调用来执行此操作。