Object References not set to an instance of an object in vb.net

Viewed 19

I designed a form that can a insert csv datas and export csv datas into excel. I used this code to run the function export csv datas into excel. but when want to export the datas into excel it come out the problems of Object References not set to an instance of an object .Do anyone have some ideas.

Please guide me.

Thanks a lot !

    Imports Microsoft.Office.Interop.Excel
Imports Microsoft.Office.Interop ''add reference for vb, else cant work export to excel




Public Class ExportClass
    Public Shared Function export()
        Dim xlApp As Excel.Application
        Dim xlWB As Excel.Workbook
        Dim xlWS As Excel.Worksheet
        Dim MisVal As Object = System.Reflection.Missing.Value
        Dim r As Integer ''use for For Loop
        Dim c As Integer ''use for For Loop



        xlApp = New Excel.Application
        xlWB = xlApp.Workbooks.Add(MisVal) ''create workbook in excel
        xlWS = xlWB.Sheets("Sheet1") ''write in new sheet



        For r = 0 To Form1.DataGridView1.RowCount - 1
            For c = 0 To Form1.DataGridView1.ColumnCount - 1
                xlWS.Cells(r + 1, c + 1) =
                    Form1.DataGridView1(c, r).Value.ToString()
                ''generate lines and cells for WSheet by reading the DGV
            Next
        Next
        Dim SFD As New SaveFileDialog
        If SFD.ShowDialog = DialogResult.OK Then
            xlWS.SaveAs(SFD.FileName & ".xlsx") ''save file name
            xlWB.Close()
            xlApp.Quit()
        End If
        releaseobj(xlApp)
        releaseobj(xlWB)
        releaseobj(xlWS)




    End Function
    Public Shared Sub releaseobj(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing



        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try



    End Sub
End Class
0 Answers
Related