Excel电子表格检查哪一行包含数据

我有一个vb.net应用程序,我打开一个包含数据的Excel电子表格。 我复制所有的数据并将其插入到SQL Server中。 find最后一行,我遇到了一个小问题。 以下是我现在正在做的事情

Dim lastRow As Long = 0 lastRow = xlws.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing).Row 

这为我find了最后一行,但通常情况下,电子表格可能包含与我试图插入到表中的数据不相关的数据 – 在这种情况下,它是电子表格最后一行的机密性声明。 所以我想要做的是设置最后一行,无论最后一行的实际数据是什么。 这是它看起来像…

在这里输入图像说明

所以在这种情况下 – 我想最后一行被识别为第11行而不是第13行。事情是 – 报告的格式可能会略有不同(对于保密声明),往往可能会开始在列A或B并被合并(可能),或者他们可能会在别处写入。

另一件事是数据的列A和B(在行11结束)可能有时不具有值。 我应该如何去做这样的事情?

编辑:这就是我想要的 – 讨厌GoTo的,但….

 LastRowCheck: If CStr(excel.Cells(lastRow, 4).Value) = "" And CStr(excel.Cells(lastRow, 5).value) = "" And CStr(excel.Cells(lastRow, 6).value) = "" Then lastRow += -1 goto LastRowCheck End If 

怎么样:

 Sub TheTrueLastRow() Dim i As Long For i = 1 To Rows.Count If Cells(i, "B").Value = "" Or Cells(i, "E").Value = "" Then lastRow = i - 1 Exit For End If Next i MsgBox lastRow End Sub 

在这里输入图像说明

也许这样的事情:

 Sub Test() MsgBox LastRow(ThisWorkbook.Worksheets(2)) End Sub Public Function LastRow(wrkSht As Worksheet) As Long Dim rLastCell As Range Dim lLastCol As Long, lLastRow As Long Dim rCol As Range On Error Resume Next With wrkSht lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row If lLastCol = 0 Then lLastCol = 1 If lLastRow = 0 Then lLastRow = 1 Set rLastCell = .Cells(lLastRow, lLastCol) 'Look at each column, if the last cell is merged then look up from there, 'otherwise leave the last row as it is. For Each rCol In .Range(.Cells(rLastCell.Row, 1), rLastCell).Columns If rCol.MergeCells Then LastRow = rCol.End(xlUp).Row Exit For Else LastRow = rLastCell.Row End If Next rCol End With On Error GoTo 0 End Function 

编辑:只是注意到,它会在这一点上失败(好吧,如果最后一列比前两个短)。

另一件事是数据的列A和B(在行11结束)可能有时不具有值。 我应该如何去做这样的事情?

如果您有一列在表的每一行中都有数据,并且在所需数据之间有一个空单元格

xlws.Range( “B1”)。完(Excel.XlDirection.xlDown).Row

或者,如果只有在列末尾没有不需要的数据,则可以采取自下而上的方法。

xlws.Range(“B”&xlws.Rows.Count).End(Excel.XlDirection.xlUp).Row

在这里输入图像说明 在这里输入图像说明