Close an open excel in VB.NET

  • Thread starter Thread starter JayWangTPE
  • Start date Start date
J

JayWangTPE

Guest
I wrote the following sub to open an excel file in a sub and close it in another sub.

When I run CloseToolStripMenuItem code to close an open excel. One exception occurs.

How can I fix this issue?

"System.NullReferenceException: 'Object reference not set to an instance of an object.'"


Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
'Dim selectfile As String
WorkbookNameBox.Text = Getfilename("*.xlsm")
selectfile = WorkbookNameBox.Text
OpenExcelDemo(WorkbookNameBox.Text)
End Sub
Private Sub OpenExcelDemo(ByVal FileName As String)
If IO.File.Exists(FileName) Then
Dim Proceed As Boolean = False
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
' Dim xlWorkSheet As Excel.Worksheet = Nothing
' Dim xlWorkSheets As Excel.Sheets = Nothing
'Dim xlCells As Excel.Range = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = True
'xlWorkSheets = xlWorkBook.Sheets
End If
End Sub

Private Sub CloseToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseToolStripMenuItem.Click
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()

End Sub

Continue reading...
 
Back
Top