在Excel宏中使用VBA打印和现有pdf

时间:2017-09-01 19:17:06

标签: excel-vba vba excel

我正在尝试检查.pdf文件是否存在。如果它存在,我想打印文件。

    Function PrintPDF(PartNum As String)
    Dim DirFile As String
    DirFile = "\\SERVER5\hpfiles\Company\Drawings\PDF-SL8\" & PartNum & ".pdf"
        If Dir(DirFile) = "" Then
    Exit Function
    Else
    DirFile.PrintOut

    End If
    End Function

我收到编译错误,说无效限定符。我假设它是因为DirFile是一个字符串。

如何将此字符串用作打印的目标文件?

1 个答案:

答案 0 :(得分:0)

正确,你不能打印一个字符串。一种方法是使用shell命令并打印文件,如下所示:

Option Explicit

Declare Function apiShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As Long

Public Sub PrintFile(ByVal strPathAndFilename As String)
    Call apiShellExecute(Application.hwnd, "print", strPathAndFilename, vbNullString, vbNullString, 0)
End Sub

Function PrintPDF(PartNum As String)
    Dim DirFile As String
    DirFile = "\\SERVER5\hpfiles\Company\Drawings\PDF-SL8\" & PartNum & ".pdf"

    If Dir(DirFile) = "" Then Exit Function

    PrintFile (DirFile)
End Function

改编自this post