Link to home
Start Free TrialLog in
Avatar of baabaa_nl
baabaa_nlFlag for United Kingdom of Great Britain and Northern Ireland

asked on

vb.net, close a file that is already open

I need the code in vb.net that will check if the file is open and then close the file.

Thanks in advance
Avatar of SiddharthRout
SiddharthRout
Flag of India image

If you are referring to an open Excel File, then you will have to loop through all open instances of Excel Workbooks and then close it. Let me know if you still want a code example?

Sid
is it when you have opened the file using your program or when another program has the file open?
Avatar of baabaa_nl

ASKER

SiddharthRout--> yes i would like a sample code.

nepaluz--> the file that was opened by another program

Thanks in advance guys
A very basic example :)

Imports Microsoft.Office.Interop.Excel

Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles Button1.Click
        Dim xlApp As New Excel.Application
        Dim xlWb As Excel.Workbook

        xlApp = GetObject(, "Excel.Application")
        For Each xlWb In xlApp.Workbooks
            xlWb.Close(False)
        Next
    End Sub
End Class

Open in new window


Note: If there are multiple instance of Excel then you might have to use TRY/CATCH to loop though all instances and then close all the workbooks.

HTH

Sid
well, could you please give me a code that can close any opened file which was opened by another application.

Cheers
ASKER CERTIFIED SOLUTION
Avatar of SiddharthRout
SiddharthRout
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you for your code. It was an excellent work.