1
我試圖寫入現有的Excel文件,但發生了NullReferenceException
錯誤。我該怎麼做才能解決它?NullReferenceException嘗試寫入已存在的Excel文件時
我參考Microsoft Excel 16.0 Object Library
。
這裏就是我所做的:
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
我試圖用一個Try-Catch
併成功阻止錯誤。但該程序不起作用。沒有錯誤,但文件沒有改變。當我將路徑和文件名更改爲不存在的路徑和文件名時,程序會執行相同的操作(無錯誤,只是不寫任何內容)。