I have a problem while I'm connecting with Excel in VB.NET. When I'm looping through the cells to find last non-empty rows inside sheet, when it comes to moment that I'm comparing value of empty cell to "" I recieve error:NullReferenceException
was caught. Object reference not set to an instance of an object."
There is a fragment of code:
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
I tried changing while condition many times to xlsheet.Cells(lRow, 3).value etc. but I always failed - the only way to make it working was by try - catch, but I'm wondering what I'm doing wrong and how to fix it in proper way?