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

时间:2017-06-02 18:33:06

标签: excel excel-vba vba

我有一个脚本,用于查找不同工作表中特定表列中的最后一个条目,并将其粘贴到主工作表列表中。它的操作是“在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

1 个答案:

答案 0 :(得分:1)

这是一种方式

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

<强>截图

enter image description here

另一种方式

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