0

I have a command button which opens the file.

But if the same file is opened for the second time it should first close it and then reopen it.

So i am looking for such code - I would be very thankful for this help.

brettdj
  • 53,759
  • 15
  • 112
  • 174
user1222679
  • 901
  • 2
  • 9
  • 6
  • 2
    What have you tried? Where are you stuck? Ypou have shown very little effor in this or any of your questions. In fact the answer to this is a very small step to the answer to one of your [earlier questions](http://stackoverflow.com/a/9382034/445425) – chris neilsen Feb 25 '12 at 21:00

2 Answers2

1

Check if it is open, if not, close it using close method.

The following code was sourced from this VBAXpress Article

Function IsFileOpen(FileName As String) 
Dim iFilenum As Long 
Dim iErr As Long 

On Error Resume Next 
iFilenum = FreeFile() 
Open FileName For Input Lock Read As #iFilenum 
Close iFilenum 
iErr = Err 
On Error Goto 0 

Select Case iErr 
Case 0:    IsFileOpen = False 
Case 70:   IsFileOpen = True 
Case Else: Error iErr 
End Select     
End Function 

Sub test() 
    If Not IsFileOpen("C:\MyTest\volker2.xls") Then 
        Workbooks.Open "C:\MyTest\volker2.xls" 
    End If 
End Sub 

If you just want to close a workbook without the user being prompted for any confirmations about saving the workbook you can simply do this :

ActiveWorkbook.Close False 

' closes the active workbook without saving any changes

ActiveWorkbook.Close True 

' closes the active workbook and saves any changes

ActiveWorkbook.Close 

' closes the active workbook and lets the user decide if changes are to be saved or not

Workbooks("BOOK1.XLS").Close SaveChanges:=False
brettdj
  • 53,759
  • 15
  • 112
  • 174
Andrew
  • 7,351
  • 13
  • 59
  • 113
0

Workbooks have a Close method.

See here

brettdj
  • 53,759
  • 15
  • 112
  • 174
Karl Barker
  • 10,697
  • 3
  • 20
  • 25