如何测试pdf是否已经打开 - 使用Excel宏

时间:2018-06-08 09:46:10

标签: excel vba excel-vba excel-2007

我们有一个生成发票的Excel电子表格。我们现在需要将电子表格转换为pdf,以便通过电子邮件发送给客户。

我写了一个宏,只需按一下按钮即可。生成.pdf并显示它(在Acrobat阅读器窗口中)。

但是,如果用户故意,或者在Acrobat窗口仍然打开时无意中第二次按下按钮 - 宏错误。

宏是:

Sub SaveAsPDF()
'
' SaveAsPDF Macro
'

'
    Application.Goto Reference:="Print_Area"

    sPath = ThisWorkbook.Path
    'add 'Document Properties' CustomerName & CustOrderRef to the pdf doc.
    ThisWorkbook.BuiltinDocumentProperties("title").Value = Range("H13").Value & "-ref:" & Range("H14") & "-" & FormatCurrency(Range("J115").Value, 2)

    'get Inv# and CustomerName
    'ThisFile = ThisWorkbook.Path & "\" & "Inv" & Range("H15").Value & "-" & Range("H13").Value & ".pdf"
    ThisFile = ThisWorkbook.Path & "\" & "Inv.pdf"

    MsgBox "The info. will now be copied to create a PDF Invoice." & vbCrLf & "Which will be saved in the 'Invoices' folder as:" & vbCrLf & ThisFile & vbCrLf & vbCrLf & "Please press OK, and when the PDF window opens - print 2 copies on Invoice Stationery." & vbCrLf & vbCrLf & "The PDF then can be closed.  (its already been saved)"
    '*** Note - this code arrors if pdf is already open !  ***


    'Create pdf. save it and display it on-screen - for user to print
    ActiveSheet.ExportAsFixedFormat _
                Type:=xlTypePDF, _
                filename:=ThisFile, _
                Quality:=xlQualityStandard, _
                IncludeDocProperties:=True, _
                IgnorePrintAreas:=False, _
                OpenAfterPublish:=True

    'save & close the spreadsheet
    ActiveWorkbook.Close SaveChanges:=True

    ThisWorkbook.Saved = True
    Application.Quit


End Sub




Function IsFileOpen(fileFullName As String)
    Dim FileNumber As Integer
    Dim errorNum As Integer

    'MgBox "123" & fileFullName

    On Error Resume Next
    FileNumber = FreeFile()   ' Assign a free file number.
    ' Attempt to open the file and lock it.
    Open fileFullName For Input Lock Read As #FileNumber
    Close FileNumber       ' Close the file.
    errorNum = Err         ' Assign the Error Number which occured
    On Error GoTo 0        ' Turn error checking on.
    ' Now Check and see which error occurred and based
    ' on that you can decide whether file is already
    ' open
    Select Case errorNum
        ' No error occurred so ErroNum is Zero (0)
        ' File is NOT already open by another user.
        Case 0
         IsFileOpen = False

        ' Error number for "Permission Denied." is 70
        ' File is already opened by another user.
        Case 70
            IsFileOpen = True

        ' For any other Error occurred
        Case Else
            Error errorNum
    End Select

End Function

我发现(在StackOverflow中)宏来测试文件是否打开(与另一个用户),其他人看到:上面的函数IsFileOpen。 但我不能让他们为我工作。例如

出现IsFileOpen错误
  

错误errorNum

我怎样才能做到最好/最简单的测试:

  1. 文件是否存在?
  2. 如果是的话,是否已经开放供阅读?

2 个答案:

答案 0 :(得分:0)

尽管我意识到它本质上是相同的功能。它看起来确实有点不同....也许应用这个并看看它是否有帮助?

Public Function IsFileOpen(FileName As String, Optional ResultOnBadFile As Variant) As Variant

Dim FileNum As Integer
Dim ErrNum As Integer
Dim V As Variant

On Error Resume Next

If Trim(FileName) = vbNullString Then
    If IsMissing(ResultOnBadFile) = True Then
        IsFileOpen = False
    Else
        IsFileOpen = ResultOnBadFile
    End If
    Exit Function
End If

V = Dir(FileName, vbNormal)
If IsError(V) = True Then
    If IsMissing(ResultOnBadFile) = True Then
        IsFileOpen = False
    Else
        IsFileOpen = ResultOnBadFile
    End If
    Exit Function
ElseIf V = vbNullString Then
    If IsMissing(ResultOnBadFile) = True Then
        IsFileOpen = False
    Else
        IsFileOpen = ResultOnBadFile
    End If
    Exit Function
End If

FileNum = FreeFile()
Err.Clear
Open FileName For Input Lock Read As #FileNum
ErrNum = Err.Number

Close FileNum
On Error GoTo 0

Select Case ErrNum
    Case 0
        IsFileOpen = False
    Case 70
        IsFileOpen = True
    Case Else
        IsFileOpen = True
End Select

End Function

我会称之为:

If IsFileOpen(ActiveWorkbook.Path & "\" & Month(Date) & "-" & Year(Date) & ".pdf") = False Then 'rest of code. Obviously you have to change path and name to your needs.

答案 1 :(得分:0)

对于“1。文件是否存在?”

Public Function fp_FilExs(pPne$) As Boolean
    fp_FilExs = CBool(LenB(Dir$(pPne, vbNormal)))
End Function

对于“2。如果是这样,它是否已经开放供阅读?”
请尝试以下代码 Tools --> Options --> General --> Error Trapping选项
必须小于Break on all errors

然而,对于所有情况,它并不是一个全面的解决方案 例如,使用文本文件,在Notepad ++中打开甚至编辑它,它不起作用......

Public Function fp_InUse(pPne$) As Boolean
Dim iFreFil%
    iFreFil = FreeFile
On Error Resume Next
    Open pPne For Input Lock Read Write As #iFreFil
    fp_InUse = CBool(Err.Number)
    Close #iFreFil
End Function


另请查看this documentation
返回以下状态:

   Select Case bResult
      Case FILE_IN_USE
         Label1.Caption = "File in use"
      Case FILE_FREE
         Label1.Caption = "File is available"
      Case FILE_DOESNT_EXIST
         Label1.Caption = "File does not exist!"
   End Select