复制表格列中的最后一个值,而不是下面的空表格行

我有一个脚本,用于在不同的工作表中查找特定表格列中的最后一个条目,并将其粘贴到主表单列表中。 它的操作是“在列B中查找最后使用的行”,但显然表格行(即使它们是空白的)算作已用过的行,因此大部分返回值都是空白的,因为我要查找的实际值是在顶部而不是在最后一行。 同样重要的是要注意,这些表单上有多个堆叠的表格,但是每个表格在B列中只有一个值,而且我只是在寻找最近的一个表格。

有没有办法告诉excel不要将空白表格作为使用过的行数? 我只想返回列B中的最后一个值,即使它不是最后一个表格行。

Dim rng As Range Dim cell As Range Dim result As String Dim result_sheet As Long Dim LastRow As Long Set rng = Range("A2:A200") For Each cell In rng result = cell.Value LastRow = Worksheets(result).Cells(Worksheets(result).Rows.Count, "B").End(xlUp).row cell.Offset(0, 1).Value = Worksheets(result).Range("B" & LastRow).Value Next cell 

这是一种方法

 Sub Sample() Dim ws As Worksheet Dim tmplRow As Long, lRow As Long, i As Long '~~> Change this to the relevant sheet Set ws = Sheet1 With ws tmplRow = .Range("B" & .Rows.Count).End(xlUp).Row For i = tmplRow To 1 Step -1 If Len(Trim(.Range("B" & i).Value)) <> 0 Then lRow = i Exit For End If Next i If lRow = 0 Then lRow = 1 MsgBox "The last row is " & lRow End With End Sub 

截图

在这里输入图像说明

另一种方式

 Sub Sample() Dim ws As Worksheet Dim tbl As ListObject Dim lRow As Long, endRow As Long, startRow As Long, i As Long '~~> Change this to the relevant sheet Set ws = Sheet1 With ws '~~> Change this to the relevant table number Set tbl = .ListObjects(1) endRow = tbl.Range.Rows.Count startRow = tbl.Range.Row For i = endRow To startRow Step -1 If Len(Trim(.Range("B" & i).Value)) <> 0 Then lRow = i Exit For End If Next i MsgBox lRow End With End Sub