尝试打开工作簿时出现空引用异常,vb.net

时间:2015-06-03 22:47:17

标签: vb.net excel nullreferenceexception

我有一个openfiledialog从文本框中读取电子表格文件名,然后执行一些格式化并吐出文本文件。代码工作正常一次;我的下一个任务是获取它,以便我可以在不关闭程序的情况下打开连续的电子表格(一次一个)。

当我尝试打开第二个excel文件时,我在打开工作簿的行上得到一个空引用异常(对象引用未设置为对象的实例)。

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()

我在这里看到两个可能的空引用:1)前一行的.ToString可能为空。 WI运行代码,文本框不会被正确的文件路径填充。只有在弹出错误框后我才会点击“继续”#39;文本框是否显示正确的路径。 2)平台问题,64x vs 32x?这出现在一个搜索中,所以我尝试了#34; New Excel.App"和#34;新的Excel.Workbook",然后改为x86平台,但这让我臭名昭着的COM异常80040154,这让我觉得这不是真正的问题,但我还是很新的编码..

有人能找到空吗?

1 个答案:

答案 0 :(得分:0)

首先,您不需要调用OpenFileDialog1.OpenFile()。事实上,您根本不需要获取文件流,因为您没有直接操作文件(只有Excel)。

其次,您需要独立检索和处理xlApp.Workbooks集合,否则您将泄漏一些COM包装器。空引用异常可以来自Workbooks集合为null,或者open filename为null。一些错误处理将解决您的问题。

...
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

请注意,我在使用后明确释放了每个COM对象,并将值设置为Nothing。这对于确保正确清理是必要的。