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

asked on

Check if excel is already open

Hello,
I n vb.net 2015 how to check if excel file is already open ?

Cheers
Avatar of D Patel
D Patel
Flag of India image

Try making a function that will check to see if the workbook is already open or not, like this:

Private Shared Function IsWorkbookAlreadyOpen(app As Excel.Application, workbookName As String) As Boolean
    Dim isAlreadyOpen As Boolean = True

    Try
        app.Workbooks.get_Item(workbookName)
    Catch theException As Exception
        isAlreadyOpen = False
    End Try

    Return isAlreadyOpen
End Function

Then you can use it in your code like this:

Private Sub btnMinSummaryWorksheet_Click(sender As Object, e As EventArgs) Handles btnMinSummaryWorksheet.Click
    'This procedure runs when the btnOpenSummaryWorksheet button is clicked. Calls the
    'Sub procedure opens the Summary Worksheet Dashboard

    Dim xlApp As New Excel.Application
    xlApp.Visible = True

    Dim xlBook As Excel.Workbook
    Dim workbookName = "F:\Test Environment\Compensation Workbook\Compensation Workbook\bin\Debug\2011.1004.Compensation Template.xlsx"
    If IsWorkbookAlreadyOpen(xlApp, workbookName) Then
        xlBook = xlApp.Workbooks.get_Item(workbookName)
    Else
        xlBook = xlApp.Workbooks.Open(workbookName)
    End If

    Dim xlSheet As Excel.Worksheet
    xlSheet = CType(xlBook.Sheets("SummaryWorksheet"), Worksheet)
    xlSheet.Activate()

    Me.Close()
End Sub
ASKER CERTIFIED SOLUTION
Avatar of D Patel
D Patel
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
Avatar of RIAS

ASKER

Thanks,

 xlApp.Workbooks.get_Item ---error not a member of workbooks?
usually it can be get solved by cleaning and rebuilding the application