Sample macro codeIf a given file is not already open, the following macro also opens it. If the file is not in the location that you specified, you receive the following error message:
Note In Microsoft Office Excel 2007, you have to change Book2.xls to Book2.xlss in the following code.
- Start Excel, and then press ALT+F11 to open Visual Basic for Applications.
- In Visual Basic, click Module on the Insert menu.
- Type the following code in the module sheet.
' Test to see if the file is open.
If IsFileOpen("c:\Book2.xls") Then
' Display a message stating the file in use.
MsgBox "File already in use!"
' Add code here to handle case where file is open by another
' Display a message stating the file is not in use.
MsgBox "File not in use!"
' Open the file in Microsoft Excel.
' Add code here to handle case where file is NOT open by another
' This function checks to see if a file is open or not. If the file is
' already open, it returns True. If the file is not open, it returns
' False. Otherwise, a run-time error occurs because there is
' some other problem accessing the file.
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
IsFileOpen = True
' Another error occurred.
ID do Artigo: 291295 - Última Revisão: 31 de jan de 2007 - Revisão: 1