【发布时间】:2016-08-25 23:37:57
【问题描述】:
我在 VB.NET 中连接 Excel 时遇到问题。当我遍历单元格以查找工作表内的最后一个非空行时,当我将空单元格的值与“”进行比较时,我收到错误:NullReferenceException 被捕获。对象引用未设置为对象的实例。"
有一段代码:
Dim xlApp As New Excel.Application
Dim xlWb As Excel.Workbook
Dim xlsheet As Excel.Worksheet
Dim lRow As Integer = 1
Dim excelFilePath As String
Using FileDialog As New OpenFileDialog
FileDialog.Title = "Please choose Excel file with XXX"
FileDialog.FileName = ""
FileDialog.ShowDialog()
excelFilePath = FileDialog.FileName
End Using
xlApp.Visible = True
xlWb = xlApp.Workbooks.Open(excelFilePath)
xlsheet = xlWb.Sheets("Sheet1")
Do While xlsheet.Cells(lRow, 3).value.ToString() <> ""
lRow += 1
Loop
我尝试将 while 条件多次更改为 xlsheet.Cells(lRow, 3).value 等,但我总是失败 - 使其工作的唯一方法是尝试 - 捕捉,但我想知道我在做什么做错了什么以及如何以正确的方式解决它?
【问题讨论】:
-
Do While xlsheet.Cells(lRow, 3) IsNot Nothing AndAlso xlsheet.Cells(lRow, 3).Value.ToString() <> ""?