Is file open?

jsic1210

Registered User.
Local time
Today, 05:55
Joined
Feb 29, 2012
Messages
188
Hello all,

In Access, I'm trying to transfer a table to a spreadsheet, but I only want to do it if the spreadsheet file is CLOSED. I have tried a few things that I've read online, but with no luck. So I want to run the following code ONLY if the file Metrics Monthly Metrics Report is closed. Here is my code:
Code:
Private Sub cmdCategoryYTD_Click()
'-----------------------------------
'Export Pending to Excel
'-----------------------------------

Dim strLoc As String
Dim strTbl As String
Dim strDest As String

    'File Name
    strLoc = "E:\MIS\"
    strTbl = "tblPending"
    strDest = strLoc & "Metrics\Monthly Metrics Report.xls"


    'Export to Excel
    DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, strTbl, strDest, True

End Sub


I should mention that I want to ensure it's not loaded on anybody's computer. (E:\ is a shared drive)
 
Last edited:
This code example adapted from this kb article.

Place the following function in a code module in your app;

Code:
Function FileLocked(strFileName As String) As Boolean
   On Error Resume Next
   ' If the file is already opened by another process,
   ' and the specified type of access is not allowed,
   ' the Open operation fails and an error occurs.
   Open strFileName For Binary Access Read Write Lock Read Write As #1
   Close #1
   ' If an error occurs, the file is currently open.
   If Err.Number <> 0 Then
      FileLocked = True
      Err.Clear
   End If
End Function

Then call it in your procedure like this;

Code:
Private Sub cmdCategoryYTD_Click()
'-----------------------------------
'Export Pending to Excel
'-----------------------------------

Dim strLoc As String
Dim strTbl As String
Dim strDest As String

    'File Name
    strLoc = "E:\MIS\"
    strTbl = "tblPending"
    strDest = strLoc & "Metrics\Monthly Metrics Report.xls"

    If FileLocked(strDest) Then
        MsgBox "File is currently open"
    Else
        'Export to Excel
        DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, strTbl, strDest, True
    End If

End Sub

I did test it on a shared drive on our network where the file was open by another computer on the network.
 
Thank you very much! I tested it across computers, too, and it works. That is a huge relief!
:cool:
----------------------------
Keep Calm and Chive On!
 
Can anyone tell me why this line of code

Code:
 Open strFileName For Binary Access Read Write Lock Read Write As #1

in the above post creates a file of the same strFileName when it runs. (my file is a .pdf and so will not open anyway as it has no data)

I am now using
Code:
 Kill strFileName
to get rid of it but I would prefer the file not to be produced in the first place.

Thanks
 
ted.martin, I only use that method for text file types not for pdfs. What's your objective?
 

Users who are viewing this thread

Back
Top Bottom