如何在EXCEL VBA中的给定范围内自动选择最后三行

时间:2017-10-27 07:02:38

标签: excel vba excel-vba

我创建了一个代码来选择数据并将数据从一个工作表粘贴到另一个工作表。但是这段代码总是在行中选择最后三个值。 我需要根据给定的范围选择数据。例如C5:C15不适用于整个c列。帮帮我

Private Sub CommandButton1_Click()

Dim LastRow1, LastRow2, LastRow3 As Long
Dim Last3Rows1, Last3Rows2, Last3Rows3 As Range

LastRow3 = Sheets("AVG-PO").Range("C" & Rows.Count).End(xlUp).Row
LastRow1 = Sheets("AVG-PO").Range("A" & LastRow3).End(xlUp).Row
LastRow2 = Sheets("AVG-PO").Range("B" & LastRow3).End(xlUp).Row

Set Last3Rows3 = Sheets("AVG-PO").Range("C" & LastRow3).Offset(-2, 0).Resize(3, 1)
Set Last3Rows1 = Sheets("AVG-PO").Range("A" & LastRow3).Offset(-2, 0).Resize(3, 1)
Set Last3Rows2 = Sheets("AVG-PO").Range("B" & LastRow3).Offset(-2, 0).Resize(3, 1)

Last3Rows1.Select
Selection.Copy Sheets("Data").Range("A30")

Last3Rows2.Select
Selection.Copy Sheets("Data").Range("B30")

Last3Rows3.Select
Selection.Copy Sheets("Data").Range("C30")

End Sub

enter image description here

1 个答案:

答案 0 :(得分:0)

不确定我完全理解你想要的范围,但你可以使用它。

Sub test()
    Dim NextFree As Long
    Dim TableStartRange As Long

    For i = 1 To 100
    Select Case Range("A" & i).Value
        Case "Table1"
            TableStartRange = i + 1 'finds table1 in A2 and then +1 before the actual table start in column C
    End Select

    NextFree = Range("C" & TableStartRange & ":C" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row ' returns the value 14 since its the first free row in column C

End Sub