Results 1 to 5 of 5

Thread: Creating and saving Excel files from VB Application

  1. #1

    Thread Starter
    New Member
    Join Date
    Mar 2018

    Creating and saving Excel files from VB Application

    Apologies if this is the wrong thread.

    I have a VB application that is generating a report, and I need to export it to an Excel file. Excel is installed on the machines this will be running on, and after using a bit of digging and mulitple net resources, I am fairly sure I am close. However, whenever I run the code, the export routine runs, and hangs, with the debugger at the 'End Sub' of the entire export Sub with an error of:

    An unhandled exception of type 'System.NullReferenceException' occurred in <program name>.exe
    Object reference not set to an instance of an object.

    I have the code below. This is run off a button on the form and driven from a DataGridView where I control the data, so there is no possibility of empty cells in the view.
    At the beginning of the form I have the following imports

    Imports Excel = Microsoft.Office.Interop.Excel
    Imports System.Data.SqlClient
    Imports System.Configuration

    Code for the routine:

    Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
            ' Handles exporting of report to Excel
            Dim xlApp As Excel.Application = New Microsoft.Office.Interop.Excel.Application()
            Dim xlWorkBook As Excel.Workbook
            Dim xlWorkSheet As Excel.Worksheet
            Dim misValue As Object = System.Reflection.Missing.Value
            Dim i As Integer
            Dim j As Integer
            xlApp = New Excel.Application
            xlWorkBook = xlApp.Workbooks.Add(misValue)
            xlWorkSheet = xlWorkBook.Sheets("sheet1")
            For Each col As DataGridViewColumn In dgvReport.Columns
                xlWorkSheet.Cells(1, col.Index + 1) = col.HeaderText.ToString
            Dim rowCount As Integer = dgvReport.Rows.Count
            MsgBox("There are " & rowCount & " Rows", vbOKOnly, "Test")
            For i = 2 To dgvReport.Rows.Count - 1
                For j = 0 To dgvReport.ColumnCount - 1
                    xlWorkSheet.Cells(i + 2, j + 1) = dgvReport(j, i).Value.ToString()
            Dim path As String = tbExcelPath.Text
            xlWorkBook.SaveAs(tbExcelPath.Text & "\" & tbReportName.Text & ".xlsx")
            xlWorkBook.Close(True, misValue, misValue)
            xlApp = Nothing
            xlWorkBook = Nothing
            xlWorkSheet = Nothing
            misValue = Nothing
        End Sub
    The Path is retrieved presently by calling for the current users Desktop directory, and the filename is auto-generated as plain text

    I have been working on this for a while, and it's starting to get to me, as I can't seem to figure out where the problem actually is. Any advice would be appreciated.

  2. #2
    Join Date
    Dec 2004

    Re: Creating and saving Excel files from VB Application

    xlWorkBook.Close(True, misValue, misValue)
    as you have already saved the workbook you do not need to save again

    i have not tested, but i would assume that the second parameter optional would need to be a valid file path if you really want to save the file, so try changing to either
    xlWorkBook.Close(True, tbExcelPath.Text & "\" & tbReportName.Text & ".xlsx", misValue)
    in the case of the first you probably would not need the SaveAs line

    you also should not need the xlWorkBook.Activate() line

    as i can not test your code i am only guessing
    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed

  3. #3

    Thread Starter
    New Member
    Join Date
    Mar 2018

    Re: Creating and saving Excel files from VB Application

    Thank you for the suggestions, sadly the error continues. I tries both options in separate tests starting from the base code.

    1) Commenting out the Save as line and changing the Close line to include the path and file name as second argument
    2) Changing he close so it only has the one argument of False

    I ran both of these options with and without the activate line present, no change in any case.

  4. #4
    PowerPoster Zvoni's Avatar
    Join Date
    Sep 2012
    To the moon and then left

    Re: Creating and saving Excel files from VB Application

    I'm in no way an .NET-Expert, but going by your Error-Description of "System.NullReferenceException":
    Have you checked, that your objects are instantiated?
    As i said: I'm no NET-expert but my money would be on your xlWorkBook or xlWorksheet-Object not being instantiated, meaning one (or both) are null
    One System to rule them all, One IDE to find them,
    One Code to bring them all, and to the Framework bind them,
    in the Land of Redmond, where the Windows lie
    People call me crazy because i'm jumping out of perfectly fine airplanes.
    For health reasons i try to avoid reading unformatted Code

  5. #5
    Frenzied Member ChrisE's Avatar
    Join Date
    Jun 2017

    Re: Creating and saving Excel files from VB Application

    Hi Theta,

    give this a try..
    'you have set the Ref. to Excel
     Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
            'save DGV to Excel
            Dim Excel As ApplicationClass = New ApplicationClass
            Dim WorkBook As Workbook = Excel.Workbooks.Add
            Dim WorkSheets As Sheets = WorkBook.Sheets
            Dim WorkSheet As Worksheet = CType(WorkSheets(1), Microsoft.Office.Interop.Excel.Worksheet)
            For i = 0 To DataGridView1.RowCount - 2
                For j = 0 To DataGridView1.ColumnCount - 1
                    For k As Integer = 1 To DataGridView1.Columns.Count
                        WorkSheet.Cells(1, k) = DataGridView1.Columns(k - 1).HeaderText
                        WorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()
        End Sub
    looking at you code again, change this line
      For i = 2 To dgvReport.Rows.Count - 1
      For i = 0 To DataGridView1.Rows.Count - 2
                For j = 0 To DataGridView1.ColumnCount - 1
                    xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, i).Value.ToString()

    Last edited by ChrisE; Dec 4th, 2018 at 05:00 AM.
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts


Click Here to Expand Forum to Full Width