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