You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET 2022读取Excel触发System.NullReferenceException求助

问题分析与解决方案

你的代码触发NullReferenceException主要有两个核心问题,修正后即可正常运行:

1. 文件名变量的引号错误

你在Open方法里把变量名strFileName用双引号括起来了,这会让程序把字符串"strFileName"当成实际文件名,而不是读取你定义的F:\DarPlr\DlrData.xlsx路径,直接导致文件找不到,进而引发异常。

正确写法应该去掉引号,直接传入变量:

xlWorkBook = xlApp.Workbooks.Open(strFileName)

2. 错误的Excel应用实例化方式

在VB.NET 2022中,Excel.ApplicationClass是旧版COM互操作的写法,现在应该直接实例化Excel.Application类,否则可能导致xlApp无法正确创建实例,出现空引用:

xlApp = New Excel.Application()

修正后的完整代码

同时建议添加Try...Finally块确保Excel进程被正确释放,避免后台残留进程:

Dim strFileName As String = "F:\DarPlr\DlrData.xlsx"

Dim xlApp As Excel.Application = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing

Try
    xlApp = New Excel.Application()
    xlWorkBook = xlApp.Workbooks.Open(strFileName)
    xlWorkSheet = CType(xlWorkBook.Worksheets("Sheet1"), Excel.Worksheet) ' 显式转换更安全

    ' 读取B2单元格值并显示
    If xlWorkSheet.Cells(2, 2).Value IsNot Nothing Then
        MsgBox(xlWorkSheet.Cells(2, 2).Value.ToString())
    Else
        MsgBox("B2单元格为空")
    End If

Catch ex As Exception
    MsgBox("执行出错:" & ex.Message)
Finally
    ' 确保资源释放
    If xlWorkBook IsNot Nothing Then
        xlWorkBook.Close(SaveChanges:=False)
    End If
    If xlApp IsNot Nothing Then
        xlApp.Quit()
        ' 释放COM对象
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
    End If
End Try

额外注意事项

  • 确保你的Excel版本和引用的Microsoft Excel 12.0 Object Library兼容,如果是高版本Excel(如2016/2019/365),建议引用对应版本的库,或者改用Microsoft.Office.Interop.Excel NuGet包,兼容性更好。
  • 运行程序时确保Excel没有被其他进程锁定,且文件路径正确(注意盘符、大小写,Sheet名称是否准确,比如是Sheet1还是sheet1,Excel默认是首字母大写)。

内容的提问来源于stack exchange,提问作者Dave

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 17:52:16