I need to be able to loop through an Excel worksheet and at the first null or empty value I'd like the loop to exit and to continue to the next line.
'Add the rows'
For Each cell In worksheetRow
If cell.Value Is Nothing Then
For index = _dataTable.Rows.Count - 1 To 0
Dim deleteRow = _dataTable.Rows(index)
If _dataTable.Rows.Contains("NULL") Then
deleteRow.Delete()
End If
Next
GoTo executeInsert
Else
row(cell.Start.Column - 2) = cell.Value.ToString.Trim()
End If
Next cell
Next
executeInsert: Try
Company.Applications.ProductionEngine.BusinessAccess.BankTargetsConfigurationBusinessAccess.ExecuteLoadFileData(_dataTable, _year)
The problem is that the For Each loops through each cell. So on the first empty cell it finds, it proceeds onto the next empty cell and so on.
This is the result that is inserted into the table.
Up until row 13, at the first null occurence, I want to exit the loop and go to my next line of code which is responsible for saving what the loop gathered so far which is up until the far right cell with value '2018' on row 12.
For the sake of completeness, this is the next block of code that connects to the database and saves the data. This is where I need to go after I find the first null occurence.
Try
Company.Applications.ProductionEngine.BusinessAccess.BankTargetsConfigurationBusinessAccess.ExecuteLoadFileData(_dataTable, _year)
Catch ex As Exception
'The data insert failed'
InformationBox1.ShowErrorMessage("An internal error occured. Please refresh the page and try again.")
End Try
InformationBox1.ShowSuccessMessage("Data Uploaded")
I have tried this and it works. Problem is if something is added to the worksheet later and the rows become 148, this won't help.
For rowNumber As Integer = 1 To 147
Dim worksheetRow = _worksheet.Cells(rowNumber, 2, rowNumber, 4)
Dim row As DataRow = _dataTable.Rows.Add()
For Each cell In worksheetRow
row(cell.Start.Column - 2) = cell.Value.ToString.Trim()
Next
Next
I have also tried this but the rows don't increment. Each row from the worksheet is read and added to the first row, each record overwrites the previous one, so here there is always one row.
Dim rowCounter As Integer = 0
While rowCounter < _worksheet.Dimension.End.Row
Dim worksheetRow = _worksheet.Cells(1, 2, _worksheet.Dimension.End.Row, 4)
Dim row As DataRow = _dataTable.Rows.Add()
For Each cell In worksheetRow
If cell.Value IsNot Nothing Then
row(cell.Start.Column - 2) = cell.Value.ToString.Trim()
End If
rowCounter += 1
Next
End While
And finally, I've tried a Do Loop. I get the same result as the While Loop above.
Do
Dim worksheetRow = _worksheet.Cells(1, 2, _worksheet.Dimension.End.Row, 4)
Dim row As DataRow = _dataTable.Rows.Add()
For Each cell In worksheetRow
row(cell.Start.Column - 2) = cell.Value.ToString.Trim()
Next
Loop Until _worksheet.Cells.Value = ""
For any clarifications please let me know.