尝试写入已存在的 Excel 文件时出现 NullReferenceException

NullReferenceException when trying to write to an Excel file that already exists

我正在尝试写入现有的 Excel 文件,但发生了 NullReferenceException 错误。我应该怎么做才能解决它?

我正在引用 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 并成功阻止了错误。但该程序不起作用。没有错误,但文件没有变化。当我将路径和文件名更改为不存在的路径和文件名时,程序会做同样的事情(没有错误,只是没有写任何东西)。

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.

这是因为 Try-Catch 没有 停止 错误。查看 MSDN 文档:

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

现在进入手头的问题。 NullReferenceException 错误的原因是因为您尚未创建 oExcel:

New 实例
Dim oExcel As New Excel.Application