简体   繁体   中英

Null reference exception when trying to open a workbook, vb.net

I've got an openfiledialog reading a spreadsheet file name from a textbox, then performing some formatting and spitting out a text file. The code works fine one time through; my next task is to get it so that I can open successive spreadsheets (one at a time) without closing the program.

When I try to open a second excel file, I get a null reference exception (object ref not set to an instance of an object) on the line where I'm opening the workbook.

Public Class Form1

Dim xlApp As New Microsoft.Office.Interop.Excel.Application
Dim xlWorkbook, xlWorkbook2 As Microsoft.Office.Interop.Excel.Workbook
Dim xlWsheet, xlWsheet2 As Microsoft.Office.Interop.Excel.Worksheet
Dim strm As System.IO.Stream
Dim FormFile As String = "C:\nitemp.tmp\QuantData.xls"

Private Sub Open_Click(sender As Object, e As EventArgs) Handles Open.Click
    'Open button code'
    OpenFileDialog1.Title = "Select a File"
    OpenFileDialog1.InitialDirectory = directory.Text 'uppermost text box, change to open a different default directory with OPEN button'
    OpenFileDialog1.RestoreDirectory = True
    OpenFileDialog1.ShowDialog()
End Sub


Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
    Dim lrow As Integer = 0

    Try
        strm = OpenFileDialog1.OpenFile()
        TextBox1.Text = OpenFileDialog1.FileName.ToString()
        xlWorkbook = xlApp.Workbooks.Open(TextBox1.Text) 'opens excel file'
        xlApp.Visible = False
        strm.Close()

I see two possible null references here: 1) the .ToString on the previous line may be empty. WI run the code, the textbox isn't being populated by the correct file path. Only after the error box pops up and I hit 'continue' does the textbox show the correct path. 2) an issue with the platform, 64x vs 32x? This came up in a search, so I tried "New Excel.App" and "New Excel.Workbook", then changed to x86 platform, yet this got me the infamous COM exception 80040154, which makes me think this is not really the issue, but I'm still pretty new to coding..

Can someone find the null?

First things first, you don't need to call OpenFileDialog1.OpenFile(). In fact you don't need to get the filestream at all as you aren't manipulating the file directly (only Excel is).

Secondly, you need to retrieve and dispose of the xlApp.Workbooks collection independently, otherwise you are going to leak some COM wrappers. The null reference exception could be from either the Workbooks collection being null, or the open filename being null. Some error handling will solve your problem.

...
Dim xlWorkbooks as Excel.Workbooks
Dim xlWorkbookOpened as Excel.Workbook

Try
    TextBox1.Text = OpenFileDialog1.FileName.ToString()
    If (TextBox1.Text IsNot Nothing) Then
        xlWorkbooks = xlApp.Workbooks
        If (xlWorkbooks IsNot Nothing) Then
            xlWorkbookOpened = xlWorkbooks.Open(TextBox1.Text) 'opens excel file'
            If (xlWorkbookOpened IsNot Nothing) Then
                ' DO WHATEVER YOU NEED TO...        
                Marshal.ReleaseComObject(xlWorkbookOpened)
                xlWorkbookOpened = Nothing
            End If
            Marshal.ReleaseComObject(xlWorkbooks)
            xlWorkbooks = Nothing
        End If
    End If

Catch ex As Exception
    ' Log error to start with...
    Trace.WriteLine(ex.Message)
End Try

Note that I've explicitly released every COM object after use and set the value to Nothing. This is necessary to ensure proper cleanup.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM