Hello:
I wrote a procedure that allows me to check if a workbook is open. If the workbook is opened, then go to the specified sheet, otherwise, open the workbook and go to the sheet.
I am having 2 issues, one is that is opening the same workbook twice when the workbook is not already opened. Second, after it opens and I close the second instance, I get this error:
System.Runtime.InteropServices.COMException was unhandled
ErrorCode=-2146827284
HResult=-2146827284
Message=Exception from HRESULT: 0x800A03EC
The error is on the bold line:
If IsWorkbookAlreadyOpen(xlApp, workbookName) Then
xlBook = xlApp.Workbooks.Open(workbookName)
Here is the rest of my code:
Private Shared Function IsWorkbookAlreadyOpen(app As Excel.Application, workbookName As String) As Boolean
Dim isAlreadyOpen As Boolean = True
Try
app.Workbooks.Open(workbookName)
Catch theException As Exception
isAlreadyOpen = False
End Try
Return isAlreadyOpen
End Function
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.Open(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
What am i doing wrong here?