1

I'm trying to write to an existing Excel file, but a NullReferenceException error occurs. What should I do to fix it?

I am referencing Microsoft Excel 16.0 Object Library.

Here's what I did:

Imports Excel = Microsoft.Office.Interop.Excel
Public Class manager
    Dim oExcel As Excel.Application
    Dim oBook As Excel.Workbook
    Dim oSheet As Excel.Worksheet
    Dim oRange As Excel.Range
    Dim box1 As Integer = 0
    Dim i As Integer = 2

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        box1 = 1
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Try
            oBook = oExcel.Workbooks.Open("C:\puthere.xlsx")
        Catch ex As NullReferenceException

        End Try

        Try
            oSheet = oBook.Worksheets("sheet1")

        Catch ex As NullReferenceException
        End Try

        Try

            oSheet.Range("B" & i).Value = box1
        Catch ex As NullReferenceException
        End Try
    End Sub

End Class

I tried using a Try-Catch and succeeded to stop the error. But the program doesn't work. No error, but no change in the file. When I changed the path and filename to one that doesn't exist, the program does the same (no error, just not writing anything).

Bugs
  • 4,356
  • 9
  • 30
  • 39
SSong
  • 13
  • 3

1 Answers1

2

I tried using a Try-Catch and succeeded to stop the error. But the program doesn't work. No error, but no change in the file.

This is because a Try-Catch doesn't stop the error. Have a look at the MSDN documentation:

Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.

Now onto the issue at hand. The reason for the NullReferenceException error is because you have yet to create a New instance of oExcel:

Dim oExcel As New Excel.Application
Bugs
  • 4,356
  • 9
  • 30
  • 39