Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 尝试写入已存在的Excel文件时出现NullReferenceException_Vb.net_Nullreferenceexception_Excel Interop - Fatal编程技术网

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

Vb.net 尝试写入已存在的Excel文件时出现NullReferenceException,vb.net,nullreferenceexception,excel-interop,Vb.net,Nullreferenceexception,Excel Interop,我正试图写入现有Excel文件,但出现NullReferenceException错误。我该怎么做才能修好它 我正在引用Microsoft Excel 16.0对象库 以下是我所做的: Imports Excel = Microsoft.Office.Interop.Excel Public Class manager Dim oExcel As Excel.Application Dim oBook As Excel.Workbook Dim oSheet As Exc

我正试图写入现有Excel文件,但出现
NullReferenceException
错误。我该怎么做才能修好它

我正在引用Microsoft Excel 16.0对象库

以下是我所做的:

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
并成功地停止了错误。但是这个程序不起作用。没有错误,但文件中没有更改。当我将路径和文件名更改为不存在时,程序也会执行相同的操作(没有错误,只是没有写入任何内容)

我尝试使用
Try Catch
并成功地停止了错误。但是这个程序不起作用。没有错误,但文件中没有更改

这是因为a不能停止错误。请查看MSDN文档:

提供一种方法来处理给定代码块中可能出现的部分或所有错误,同时仍在运行代码

现在谈谈手头的问题。出现
NullReferenceException
错误的原因是您尚未创建
oExcel
新实例:

Dim oExcel As New Excel.Application